CoolFunctions.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081

#region Network Calcuators

<#
    .SYNOPSIS
        Converts a CIDR or Prefix Length as string to a Subnet Mask
    .PARAMETER CIDR
        The CIDR or Prefix Length to convert
 
#>

Function ConvertTo-SubnetMaskFromCIDR
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [String[]]
        $CIDR
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($IpRange in $CIDR)
        {
            $NetMask="0.0.0.0"
            $CIDRLength=[System.Convert]::ToInt32(($IpRange.Split('/')|Select-Object -Last 1).Trim())
            Write-Debug "[ConvertTo-SubnetMaskFromCIDR] Converting Prefix Length $CIDRLength from input $IpRange"
            switch ($CIDRLength) {
                {$_ -gt 0 -and $_ -lt 8}
                {
                    $binary="$( "1" * $CIDRLength)".PadRight(8,"0")
                    $o1 = [System.Convert]::ToInt32($binary.Trim(),2)
                    $NetMask = "$o1.0.0.0"
                    break
                }
                8 {$NetMask="255.0.0.0"}
                {$_ -gt 8 -and $_ -lt 16}
                {
                    $binary="$( "1" * ($CIDRLength - 8))".PadRight(8,"0")
                    $o2 = [System.Convert]::ToInt32($binary.Trim(),2)
                    $NetMask = "255.$o2.0.0"
                    break
                }
                16 {$NetMask="255.255.0.0"}
                {$_ -gt 16 -and $_ -lt 24}
                {
                    $binary="$("1" * ($CIDRLength - 16))".PadRight(8,"0")
                    $o3 = [System.Convert]::ToInt32($binary.Trim(),2)
                    $NetMask = "255.255.$o3.0"
                    break
                }
                24 {$NetMask="255.255.255.0"}
                {$_ -gt 24 -and $_ -lt 32}
                {
                    $binary="$("1" * ($CIDRLength - 24))".PadRight(8,"0")
                    $o4 = [convert]::ToInt32($binary.Trim(),2)
                    $NetMask= "255.255.255.$o4"
                    break
                }
                32 {$NetMask="255.255.255.255"}
            }
            Write-Output $NetMask            
        }
    }
    END
    {
        
    }
}

<#
    .SYNOPSIS
        Converts a CIDR as string to a network address
    .PARAMETER CIDR
        The CIDR to convert
#>

Function ConvertTo-NetworkAddressFromCIDR
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [String[]]
        $CIDR
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($IpRange in $CIDR)
        {
            $IpString=$IpRange.Split("/")|Select-Object -First 1
            $PrefixLength=[System.Convert]::ToInt32(($IpRange.Split("/")|Select-Object -Last 1))
            [System.Net.IPAddress]$IpAddress=$null
            if([System.Net.IPAddress]::TryParse($IpString,[ref]$IpAddress))
            {
                $AddressBytes=$IpAddress.GetAddressBytes()
                [Array]::Reverse($AddressBytes)
                $IpAsUint=[System.BitConverter]::ToInt32($AddressBytes,0)
                #Bitwise AND the NetMask and the IP
                $NetMask=[Convert]::ToUInt32(("1" * $PrefixLength).PadRight(32, "0"), 2)
                $NetAddressBytes=[BitConverter]::GetBytes(($IpAsUint -band $NetMask))
                [System.Array]::Reverse($NetAddressBytes)
                $NetAddressAsIp=New-Object System.Net.IPAddress -ArgumentList (,$NetAddressBytes)
                Write-Output $NetAddressAsIp.IPAddressToString
            }
            else
            {
                throw "Unable to parse the IP Address from $IpRange"
            }
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Converts a CIDR as string to a broadcast address
    .PARAMETER CIDR
        The CIDR to convert
#>

Function ConvertTo-BroadcastAddressFromCIDR
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [String[]]
        $CIDR
    )
    BEGIN
    {

    }
    PROCESS
    {
        
        foreach ($IpRange in $CIDR)
        {
            $IpString=$IpRange.Split("/")|Select-Object -First 1
            $PrefixLength=[System.Convert]::ToInt32(($IpRange.Split("/")|Select-Object -Last 1))
            [System.Net.IPAddress]$IpAddress=$null
            if([System.Net.IPAddress]::TryParse($IpString,[ref]$IpAddress))
            {
                $AddressBytes=$IpAddress.GetAddressBytes()
                [Array]::Reverse($AddressBytes)
                $IpAsUint=[System.BitConverter]::ToInt32($AddressBytes,0)
                #Bitwise OR the Host Mask and the IP
                $HostMask = [Convert]::ToUInt32("1" * (32 - $PrefixLength), 2)
                $NetAddressBytes=[BitConverter]::GetBytes(($IpAsUint -bor $HostMask))
                [System.Array]::Reverse($NetAddressBytes)
                $NetAddressAsIp=New-Object System.Net.IPAddress -ArgumentList (,$NetAddressBytes)
                Write-Output $NetAddressAsIp.IPAddressToString
            }
            else
            {
                throw "Unable to parse the IP Address from $IpRange"
            }  
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Converts a CIDR as string to the last address
    .PARAMETER CIDR
        The CIDR to convert
#>

Function ConvertTo-NetworkRangeEndFromCIDR
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [String[]]
        $CIDR
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($IpRange in $CIDR)
        {
                $IpString=$IpRange.Split("/")|Select-Object -First 1
                $PrefixLength=[System.Convert]::ToInt32(($IpRange.Split("/")|Select-Object -Last 1))
                [System.Net.IPAddress]$IpAddress=$null
                if([System.Net.IPAddress]::TryParse($IpString,[ref]$IpAddress))
                {
                    $AddressBytes=$IpAddress.GetAddressBytes()
                    [Array]::Reverse($AddressBytes)
                    $IpAsUint=[System.BitConverter]::ToInt32($AddressBytes,0)
                    #Bitwise OR the Host Mask and the IP
                    $HostMask = [Convert]::ToUInt32("1" * (32 - $PrefixLength), 2)
                    $LastAddress=($IpAsUint -bor $HostMask)-1
                    $NetAddressBytes=[BitConverter]::GetBytes($LastAddress)
                    [System.Array]::Reverse($NetAddressBytes)
                    $NetAddressAsIp=New-Object System.Net.IPAddress -ArgumentList (,$NetAddressBytes)
                    Write-Output $NetAddressAsIp.IPAddressToString
                }
                else
                {
                    throw "Unable to parse the IP Address from $IpRange"
                }     
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Converts a Subnet Mask to a Prefix Length
    .PARAMETER SubnetMask
        The SubnetMask to convert
#>

Function ConvertTo-PrefixLengthFromSubnetMask
{
    [CmdletBinding()]
    [OutputType([Int32])]
    param
    (
        # Subnet Mask
        [ValidatePattern("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")]
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string[]]
        $SubnetMask
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($NetMask in $SubnetMask)
        {
            [System.Net.IPAddress]$SubnetAsIp=$null
            if([System.Net.IPAddress]::TryParse($NetMask,[ref]$SubnetAsIp))
            {
                $MaskString=[String]::Empty
                foreach ($AddressByte in $SubnetAsIp.GetAddressBytes())
                {
                    $MaskString+=[Convert]::ToString($AddressByte,2)
                }
                $MaskString=$MaskString -Replace '[\s0]'
                Write-Output $MaskString.Length
            }
            else
            {
                throw "Unable to parse the Subnet Mask $$NetMask"
            }
        }
    }
    END
    {

    }
}

#endregion

#region File Copy/Compress Methods

<#
    .SYNOPSIS
        Compresses the contents of the specified folder to a Zip file
    .PARAMETER FileName
        The path to the file to be created
    .PARAMETER SourcePath
        The path of the content to compress
    .PARAMETER File
        The file to be created
    .PARAMETER Source
        The source of the content
    .PARAMETER Overwrite
        Overwrite an existing file
    .PARAMETER IncludeParent
        Include the specified folder within the archive
    .PARAMETER OptimalCompression
        Use optimal compression
    .PARAMETER FastestCompression
        Use fastest compression
#>

function Compress-ZipFileFromFolder
{
    [CmdletBinding(DefaultParameterSetName='string')]
    param
    (
        [Parameter(Position=0,Mandatory=$true,ParameterSetName='string')]
        [System.String]$FileName,
        [Parameter(Position=1,Mandatory=$true,ParameterSetName='string')]
        [System.String]$SourcePath,
        [Parameter(Position=0,Mandatory=$true,ParameterSetName='io')]
        [System.IO.FileInfo]$File,
        [Parameter(Position=1,Mandatory=$true,ParameterSetName='io')]
        [System.IO.FileSystemInfo]$Source,
        [Parameter(Position=2,ParameterSetName='string')]
        [Parameter(Position=2,ParameterSetName='io')]
        [Switch]$OverWrite,
        [Parameter(Position=3,ParameterSetName='string')]
        [Parameter(Position=3,ParameterSetName='io')]
        [bool]$IncludeParent=$true,
        [Parameter(Position=4,ParameterSetName='string')]
        [Parameter(Position=4,ParameterSetName='io')]
        [bool]$OptimalCompression=$true,
        [Parameter(Position=5,ParameterSetName='string')]
        [Parameter(Position=5,ParameterSetName='io')]
        [Switch]$FastestCompression
    )
    $Parent=$false
    if($IncludeParent)
    {
        Write-Debug "[Compress-ZipFileFromFolder] -IncludeParent Switch Specified"
        $Parent=$true
    }
    if($PSCmdlet.ParameterSetName -eq 'io')
    {
        $FileName=$File.FullName
        $SourcePath=$Source.FullName
    }
    if($OverWrite)
    {
        Write-Debug "[Compress-ZipFileFromFolder] -Overwrite Switch Specified"
        if(Test-Path -Path $FileName)
        {
            Write-Warning "[Compress-ZipFileFromFolder] Deleting $FileName"
            Remove-Item -Path $FileName -Force
        }
    }

   if($OptimalCompression)
   {
        Write-Debug "[Compress-ZipFileFromFolder] -Overwrite Switch Specified"
        $CompressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   }
   [System.IO.Compression.ZipFile]::CreateFromDirectory($SourcePath,$FileName, $CompressionLevel, $Parent)
   Write-Verbose "[Compress-ZipFileFromFolder] Created Zip File $FileName"
}

<#
    .SYNOPSIS
        Downloads a file from a URL to the specified location
    .PARAMETER Source
        The uri of the item to download
    .PARAMETER DownloadPath
        The path of the downloaded file
#>

Function Copy-WebFile
{
    [CmdletBinding(ConfirmImpact='None')]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [System.Uri[]]$Source,
        [Parameter(Mandatory=$false)]
        [System.String]$DownloadPath=(Join-Path $env:USERPROFILE "Downloads"),
        [Parameter(Mandatory=$false)]
        [Int]$BufferLength=1MB,
        [Parameter(Mandatory=$false)]
        [Int]$TimeOutInSec=360,
        [Parameter(Mandatory=$false)]
        [Int]$ActivityId=90210          
    )

    BEGIN
    {

    }
    PROCESS
    {
        foreach ($Uri in $Source)
        {
            $StopWatch=[System.Diagnostics.Stopwatch]::StartNew()
            $FileName=Split-Path $Uri.AbsolutePath -Leaf
            $Destination=New-Object System.IO.FileInfo((Join-Path $DownloadPath $FileName))
            $Activity="Downloading $Uri to $Destination"
            Write-Progress -Id $ActivityId -Activity $Activity -Status 'Beginning Download'
            Write-Verbose "[Copy-WebFile] Downloading $Uri->$Destination"
            $DownloadedBytes=0
            $HttpRequest=[System.Net.HttpWebRequest]::Create($Uri)
            $HttpRequest.TimeOut=$TimeOutInSec*1000
            [System.Net.HttpWebResponse]$Response=$null
            [System.IO.Stream]$ResponseStream=[System.IO.Stream]::Null
            [System.IO.Stream]$TargetStream=$Destination.OpenWrite()
            try
            {
                $Response=$HttpRequest.GetResponse()
                Write-Verbose "[Copy-WebFile] Received a response of $($Response.ContentType) size $($Response.ContentLength)"
                $TotalSize=$Response.ContentLength
                $TotalSizeInMb=[System.Math]::Floor($TotalSize / 1MB)                
                $ResponseStream=$Response.GetResponseStream()
                $ReadBuffer=New-Object Byte[]($BufferLength)
                $ReadCount=$ResponseStream.Read($ReadBuffer,0,$ReadBuffer.Length)
                $DownloadedBytes+=$ReadCount
                while ($ReadCount -gt 0)
                {
                    $TargetStream.Write($ReadBuffer,0,$ReadCount)
                    $ReadCount=$ResponseStream.Read($ReadBuffer,0,$ReadBuffer.Length)
                    $DownloadedBytes+=$ReadCount
                    $CurrentlyDownloaded=[System.Math]::Floor($downloadedBytes / 1MB)
                    $CurrentProgress=[int](($DownloadedBytes / $TotalSize) * 100)
                    $CurrentSpeed=($DownloadedBytes/1MB/$StopWatch.Elapsed.TotalSeconds).ToString("#.##")
                    $CurrentStatus = "Downloaded $($CurrentlyDownloaded) MB of $($TotalSizeInMb)MB). ($CurrentSpeed MB/Sec)"
                    Write-Progress -Id $ActivityId -Activity $Activity -Status $CurrentStatus -PercentComplete $CurrentProgress
                    #Write-Verbose "[Copy-WebFile] Read: $ReadCount bytes. $CurrentStatus %$($CurrentProgress) completed."
                }
                Write-Progress -Id $ActivityId -Activity $Activity -Completed
                $StopWatch.Stop()
            }
            catch
            {
                Write-Warning "[Copy-WebFile] Error $Uri->$Destination $_"
            }
            finally
            {
                $TargetStream.Close()
                if ($Response -ne $null) {
                    $ResponseStream.Close()
                    $Response.Dispose()
                }
            }
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Copies a file with a progress stream
    .PARAMETER From
        The file to be copied
    .PARAMETER To
        The destination file
    .PARAMETER ToDirectory
        The destination directory
    .PARAMETER ActivityName
        The Progress ActivityName
    .PARAMETER ActivityId
        The Progress Activity Id
    .PARAMETER ParentActivityId
        The Parent Activity
 
#>

Function Copy-FileWithProgress
{
    [CmdletBinding(DefaultParameterSetName='fileinfo')]
    param
    (
        [Parameter(Mandatory=$true,ParameterSetName='fileinfo',ValueFromPipeline=$true)]
        [Parameter(Mandatory=$true,ParameterSetName='dirinfo',ValueFromPipeline=$true)]
        [System.IO.FileInfo[]]
        $From,
        [Parameter(Mandatory=$true,ParameterSetName='fileinfo')]
        [System.IO.FileInfo]
        $To,
        [Parameter(Mandatory=$true,ParameterSetName='dirinfo')]
        [System.IO.DirectoryInfo]
        $ToDirectory,
        [Parameter(Mandatory=$false,ParameterSetName='dirinfo')]
        [Parameter(Mandatory=$false,ParameterSetName='fileinfo')]
        [System.String]
        $ActivityName="Copying file",
        [Parameter(Mandatory=$false,ParameterSetName='fileinfo')]
        [Parameter(Mandatory=$false,ParameterSetName='dirinfo')]
        [System.Int32]
        $ActivityId=80085,
        [Parameter(Mandatory=$false,ParameterSetName='dirinfo')]
        [Parameter(Mandatory=$false,ParameterSetName='fileinfo')]
        [System.Int32]
        $ParentActivityId=0,
        [Parameter(Mandatory=$false,ParameterSetName='dirinfo')]
        [Parameter(Mandatory=$false,ParameterSetName='fileinfo')]
        [uint32]$BufferLength=1MB
    )

    BEGIN
    {

    }
    PROCESS
    {
        foreach ($item in $From)
        {
            if($PSCmdlet.ParameterSetName -eq 'dirinfo')
            {
                if(-not $ToDirectory.Exists)
                {
                    New-Item -Path $ToDirectory.Parent.FullName -Name $ToDirectory.Name -ItemType Directory -Force|Out-Null
                }
                $To=New-Object System.IO.FileInfo((Join-Path $ToDirectory.FullName $From.Name))
                Write-Verbose "[Copy-FileWithProgress] Directory option specified -> $($To.FullName)"
            }
            $ffile = $item.OpenRead()
            $Tofile = $To.OpenWrite()
            $CurrentProgress=0
            $FileSizeInMb=$item.Length/1MB
            $StopWatch=[System.Diagnostics.Stopwatch]::StartNew()
            Write-Verbose "[Copy-FileWithProgress] BEGIN:Copying $item -> $To ..."
            Write-Progress -Id $ActivityId -Activity $ActivityName `
                -ParentId $ParentActivityId `
                -Status "Copying $item -> $To" `
                -PercentComplete $CurrentProgress
            try
            {
                [System.Byte[]]$FileBuffer = New-Object System.Byte[] $BufferLength
                [long]$Total = [long]$ReadCount = 0
                [long]$TotalCopiedInMb=0
                do
                {
                    $ReadCount = $ffile.Read($FileBuffer, 0, $FileBuffer.Length)
                    $Tofile.Write($FileBuffer, 0, $ReadCount)
                    $Total += $ReadCount
                    $TotalCopiedInMb=$Total/1MB
                    $CurrentSpeed=($TotalCopiedInMb/$StopWatch.Elapsed.TotalSeconds).ToString("#.##")
                    if ($Total % 1mb -eq 0)
                    {
                        $CurrentProgress=[int]($TotalCopiedInMb/$FileSizeInMb * 100)
                        Write-Progress -Id $ActivityId `
                        -Activity "$ActivityName %$CurrentProgress"`
                        -ParentId $ParentActivityId `
                        -Status "Copying $item -> $To ($($TotalCopiedInMb.ToString("#.##")) of $($FileSizeInMb.ToString("#.##")) Mb) $($CurrentSpeed) MB/s" `
                        -PercentComplete $CurrentProgress
                    }
                } while ($ReadCount -gt 0)
                Write-Progress -Id $ActivityId -Activity $ActivityName `
                    -ParentId $ParentActivityId `
                    -PercentComplete $CurrentProgress -Completed
                $StopWatch.Stop()
                Write-Verbose "END:Copy $item -> $To Took:$($StopWatch.ElapsedMilliseconds)ms. $($CurrentSpeed) MB/s"
            }
            catch [System.IO.IOException],[System.Exception]
            {
                Write-Warning "[Copy-FileWithProgress] Error Copying File $($From.FullName) $_"
            }
            finally
            {
                $ffile.Dispose()
                $Tofile.Dispose()
                if($StopWatch -ne $null -and $StopWatch.IsRunning)
                {
                    $StopWatch.Stop()
                }
            }
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Converts a file to a Base64 string
    .PARAMETER
    .PARAMETER FilePath
        The path to the file to be created
#>

function Export-Base64StringToFile
{
    [CmdletBinding()]
    [OutputType([System.IO.FileInfo])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [String]
        $Base64String,
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
        [String]
        $FilePath,
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
        [Switch]
        $Force
    )

    if ((Test-Path -Path $FilePath) -and $Force.IsPresent -eq $false) {
        throw "$FilePath already exists! Specify -Force to Overwrite"
    }
    $ContentBytes=[Convert]::FromBase64String($Base64String)
    $ContentBytes|Set-Content -Path $FilePath -Encoding Byte -Force:$Force.IsPresent
    Get-Item -Path $FilePath
}

<#
    .SYNOPSIS
        Converts a file to a Base64 string
    .PARAMETER File
        The file to be converted
#>

function Export-FileToBase64String
{
    [CmdletBinding(ConfirmImpact='None')]
    [OutputType([System.String])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [System.IO.FileInfo[]]
        $File
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($item in $File)
        {
            try
            {
                $FileContentBytes=Get-Content -Path $item.FullName -Encoding Byte -ErrorAction Stop
                $FileAsString=[Convert]::ToBase64String($FileContentBytes)
                Write-Output $FileAsString
            }
            catch {
                Write-Warning "[Export-FileToBase64String] Failed gathering Base64 string for $($item.FullName) $_"
            }
        }
    }
    END
    {

    }
}

#endregion

#region Time Functions

<#
    .SYNOPSIS
        Converts a Unix Timestamp to DateTime
    .PARAMETER UnixTime
        The Unix Timestamp to be converted
#>

Function ConvertFrom-UnixTime
{
    [OutputType([System.DateTime])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [double[]]
        $UnixTime
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($item in $UnixTime)
        {
            $epoch = New-Object System.DateTime(1970, 1, 1, 0, 0, 0, 0)
            $DateTime=$epoch.AddSeconds($item)
            Write-Output $DateTime
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Converts a DateTime to a Unix Timestamp
    .PARAMETER DateTime
        The DateTime to be converted
#>

Function ConvertTo-UnixTime
{
    [OutputType([System.Double])]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [datetime[]]
        $DateTime
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($item in $DateTime)
        {
            $epoch = New-Object System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            $delta = $item - $epoch;
            $UnixTime=[Math]::Floor($delta.TotalSeconds)
            Write-Output $UnixTime
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
    Converts a DateTime to ISO 5601 Time string
#>

Function ConvertTo-Iso8601Time
{
    [OutputType([String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [System.DateTime[]]
        $Time
    )
    BEGIN
    {

    }
    PROCESS
    {
        foreach ($item in $Time)
        {
            $Offset=New-Object System.DateTimeOffset($item)
            $IsoTime=$Offset.ToString('o')
            Write-Output $IsoTime
        }
    }
    END
    {

    }
}

#endregion

<#
    .SYNOPSIS
        Resize an image using the specified scaling factor
    .PARAMETER Source
        The image to be resized
    .PARAMETER Destination
        The output path for the resized image
    .PARAMETER Scale
        The scaling factor to apply
#>

Function Resize-Image
{
    [CmdletBinding()]
    [OutputType([void])]
    param
    (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true,ParameterSetName='io')]
        [System.IO.FileInfo[]]$Source,
        [Parameter()]
        [System.String]$Destination = $env:TEMP,
        [Parameter()]
        [System.Double]$Scale = 0.50
    )
    BEGIN
    {
        $ScaleTransform=New-Object System.Windows.Media.ScaleTransform($Scale,$Scale)
    }
    PROCESS
    {
        foreach($item in $Source)
        {
            Write-Verbose "[Resize-Image] Resizing image $($item.FullName)->$destinationPath using Scale ScaleTransform $Scale"
            #Prevent the file from getting locked
            $ImageSource=New-Object System.Windows.Media.Imaging.BitmapImage
            $ImageSource.BeginInit()
            $ImageSource.UriSource=$item.FullName
            $ImageSource.CacheOption=[System.Windows.Media.Imaging.BitmapCacheOption]::OnLoad
            $ImageSource.EndInit()
            ## Open and resize the image
            $image = New-Object System.Windows.Media.Imaging.TransformedBitmap ($ImageSource,$ScaleTransform)
            ## Put it on the clipboard (just for fun)
            #[System.Windows.Clipboard]::SetImage($image)

            $destinationPath=Join-Path $Destination $item.Name
            ## Write out an image file:
            $stream = [System.IO.File]::Open($destinationPath, "OpenOrCreate")
            $encoder = New-Object System.Windows.Media.Imaging.$($item.Extension.Substring(1))BitmapEncoder
            $encoder.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($image))
            $encoder.Save($stream)
            Write-Verbose "[Resize-Image] Saved $destinationPath"
            $stream.Dispose()
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Formats and indents an XmlDocument to a string
    .PARAMETER Xml
        An XmlDocument to be formatted
    .PARAMETER XmlString
        A valid string of an XML document
 
#>

Function Format-XML
{
    [CmdletBinding(DefaultParameterSetName="dom")]
    Param
    (
        [Parameter(Position=0,ValueFromPipeLine=$true,Mandatory=$true,ParameterSetName="dom")]
        [System.Xml.XmlDocument[]]$Xml,
        [Parameter(Position=0,ValueFromPipeLine=$true,Mandatory=$true,ParameterSetName="string")]
        [System.String[]]$XmlString
    )
    BEGIN
    {

    }
    PROCESS
    {
        if($PSCmdlet.ParameterSetName -eq "string")
        {
            foreach($RawXml in $XmlString)
            {
                $Doc=New-Object System.Xml.XmlDocument
                $Doc.LoadXml($RawXml)
                $Xml+=$Doc
            }
        }
        foreach ($item in $Xml)
        {
            $StringWriter=New-Object System.IO.StringWriter
            $TextWriter=New-Object System.Xml.XmlTextWriter($StringWriter)
            $TextWriter.Formatting = [System.Xml.Formatting]::Indented
            $item.WriteContentTo($TextWriter)
            Write-Output $StringWriter.ToString()         
        }
    }
    END
    {

    }
}

<#
    .SYNOPSIS
        Simple constructor wrapper for PSCredential
    .PARAMETER UserName
        The UserName
    .PARAMETER Password
        The Password as a SecureString
    .PARAMETER ClearPassword
        The Password as plain text
#>

Function New-PSCredential
{
    [OutputType([SecureString])]
    [CmdletBinding(DefaultParameterSetName='Secure')]
    param
    (
        [Parameter(Mandatory=$true,ParameterSetName='Secure')]
        [Parameter(Mandatory=$true,ParameterSetName='Plain')]
        [string]
        $UserName,
        [Parameter(Mandatory=$true,ParameterSetName='Secure')]
        [securestring]
        $Password,
        [Parameter(Mandatory=$true,ParameterSetName='Plain')]
        [string]
        $ClearPassword
    )

    if($PSCmdlet.ParameterSetName -eq 'Plain')
    {
        $Password=ConvertTo-SecureString -String $ClearPassword -AsPlainText -Force
    }
    $Credential=New-Object PSCredential($UserName,$Password)
    return $Credential
}

<#
    .SYNOPSIS
        Converts a PSCredential to as Basic Authorization string
    .PARAMETER Credential
        The PSCredential to be converted
    .PARAMETER AsHeader
        Returns in the format of a header (e.g. "Basic [YourHeader]")
#>

function ConvertTo-BasicAuth
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [pscredential[]]
        $Credential,
        [Parameter(Mandatory=$false)]
        [Switch]
        $AsHeader
    )
    begin
    {

    }

    process
    {
        foreach ($item in $Credential)
        {
            $AuthInfo="$($item.UserName):$($item.GetNetworkCredential().Password)"
            $BasicCredential = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($AuthInfo))
            if ($AsHeader.IsPresent) {
                Write-Output "Basic $BasicCredential"
            }
            else {
                Write-Output $BasicCredential
            }
        }
    }
    end
    {

    }
}

<#
    .SYNOPSIS
        Returns an XML element as a string or pscustomobject value
    .PARAMETER Element
        The XML elements to be converted
    .REMARKS
        This should go away
#>

function ConvertFrom-XmlElement
{
    [CmdletBinding(ConfirmImpact='None')]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [System.Xml.XmlElement[]]
        $Element
    )

    BEGIN
    {

    }
    PROCESS
    {
        foreach ($XElement in $Element)
        {
            $ChildElements=$XElement.SelectNodes('*')
            $ChildAttributes=$XElement.SelectNodes('@*')
            if($ChildElements.Count -gt  0 -or $ChildAttributes.Count -gt 0)
            {
                #An object or array
                $ElementProperties=[ordered]@{}
                if($ChildAttributes.Count -gt 0)
                {
                    foreach ($ChildAttribute in $ChildAttributes)
                    {
                        $ElementProperties.Add($ChildAttribute.LocalName,$ChildAttribute.Value)
                    }
                }
                if($ChildElements.Count -gt 0)
                {
                    Write-Verbose "$($XElement.LocalName) - Processing Child Elements"
                    $ChildElementsGroups=$ChildElements|Group-Object -Property LocalName
                    foreach ($ChildElementsGroup in $ChildElementsGroups)
                    {
                        if($ChildElementsGroup.Count -gt 1)
                        {
                            $IsArray=$true;
                            $ChildValue=@()
                        }
                        else
                        {
                            $IsArray=$false
                            $ChildValue=$null
                        }
                        foreach ($ChildElement in $ChildElementsGroup.Group)
                        {
                            if($IsArray)
                            {
                                $ChildValue+=(ConvertFrom-XmlElement -Element $ChildElement)
                            }
                            else
                            {
                                $ChildValue=ConvertFrom-XmlElement -Element $ChildElement
                            }
                        }
                        $ElementProperties.Add($ChildElementsGroup.Name,$ChildValue)
                    }
                }
                $ElementValue=New-Object PSObject -Property $ElementProperties
            }
            else
            {
                #Just a value
                $ElementValue=$XElement.InnerText
            }
            Write-Output $ElementValue
        }
    }
    END
    {
    }
}

<#
    .SYNOPSIS
        Returns an XML document as a pscustomobject
    .PARAMETER Element
        The XML elements to be converted
    .PARAMETER Document
        The XML documents to be converted
    .PARAMETER Flatten
        Whether to flatten the top-level object graph
    .REMARKS
        This should go away
#>

function ConvertFrom-Xml
{
    [CmdletBinding(DefaultParameterSetName='element',ConfirmImpact='None')]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='element')]
        [System.Xml.XmlElement[]]
        $Element,
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='document')]
        [System.Xml.XmlDocument[]]
        $Document,
        [Parameter(Mandatory=$false,ParameterSetName='element')]
        [Parameter(Mandatory=$false,ParameterSetName='document')]
        [Switch]
        $Flatten
    )
    BEGIN
    {

    }
    PROCESS
    {
        if($PSCmdlet.ParameterSetName -eq 'document')
        {
            $Element=@($Document|Select-Object -ExpandProperty DocumentElement)
        }
        foreach ($XElement in $Element)
        {
            $ElementValue=ConvertFrom-XmlElement -Element $XElement
            if ($Flatten.IsPresent) {
                Write-Output $ElementValue
            }
            else {
                Write-Output (New-Object PSObject -Property @{$XElement.LocalName=$ElementValue})
            }
        }
    }
    END
    {

    }
}