FileSystem.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
#region Get-DuplicateItems
function Get-DuplicateItems
{
    <#
    .Synopsis
    Finds duplicate files.
 
    .Description
    Returns a list of groups of duplicate files within a folder tree
 
    .Parameter Path
    The path to process.
     
    .Example
    Get-DuplicateItems c:\temp
    #>
 

    param (
        [string]
        $Path
    )

    if (-not $Path) {
        if ((Get-Location).Provider.Name -ne 'FileSystem') {
            Write-Error 'Specify a file system path explcitly, or change the current location to a file system path.'
            return
        }
        $Path = (Get-Location).ProviderPath
    }

    Get-ChildItem -Path $Path -Recurse -File |
        Where-Object { $_.Length -gt 0 } |
            Group-Object -Property Length |
                Where-Object { $_.Count -gt 1 } |
                    ForEach-Object {
                        $_.Group |
                            ForEach-Object {
                                $_ |
                                    Add-Member -MemberType NoteProperty -Name ContentHash -Value (_Get-MD5 -Path $_.FullName)
                            }
                        $_.Group |
                            Group-Object -Property ContentHash |
                                Where-Object { $_.Count -gt 1 }
                    }
}
#endregion

#region Test-DuplicateFile
function Test-DuplicateFile()
{
    <#
    .Synopsis
    Tests if two files are identical.
 
    .Description
    Tests if two files are identical by comparing their MD5 hashes.
 
    .Parameter FirstFile
    The path to the first file.
     
    .Parameter SecondFile
    The path to the second file
 
    .Example
    Test-DuplicateFile -FirstFile .\file1.txt -SecondFile .\file2.txt
    #>
 

    param (
        [string]
        $FirstFile,
        [string]
        $SecondFile
    )

    if( (Test-Path $FirstFile) -eq $false)
    {
        Write-Error "First file does not exist."
        return $false
    }

    if( (Test-Path $SecondFile) -eq $false)
    {
        Write-Error "Second file does not exist."
        return $false
    }

    $p1 = Resolve-Path $FirstFile
    $p2 = Resolve-Path $SecondFile

    if( (_Get-MD5 $p1) -eq (_Get-MD5 $p2))
    {
        return $true
    }
    else
    {
        return $false
    }
}
#endregion

#region Test-DuplicateDirectory
function Test-DuplicateDirectory()
{
    <#
    .Synopsis
    Tests if two directories are identical.
 
    .Description
    Tests if two directories are identical by comparing their structure and file MD5 hashes.
 
    .Parameter FirstDirectory
    The path to the first directory.
     
    .Parameter SecondDirectory
    The path to the second directory
 
    .Example
    Test-DuplicateDirectory -FirstDirectory .\dir1 -SecondDirectory .\dir2
    #>
 

    param (
        [string]
        $FirstDirectory,
        [string]
        $SecondDirectory
    )

    # Test first directory path
    if( (Test-Path $FirstDirectory) -eq $false)
    {
        Write-Error "Could not locate FirstDirectory."
        return $false
    }

    $FirstDirectory = Resolve-Path $FirstDirectory

    # Test second directory path
    if( (Test-Path $SecondDirectory) -eq $false)
    {
        Write-Error "Could not locate SecondDirectory."
        return $false
    }

    $SecondDirectory = Resolve-Path $SecondDirectory

    # Get the count of directories on both subtrees
    $FirstDirectoryDirectoryCount = (Get-ChildItem $FirstDirectory -Recurse -Force -Directory | Measure-Object).Count
    $SecondDirectoryDirectoryCount = (Get-ChildItem $SecondDirectory -Recurse -Force -Directory | Measure-Object).Count
    
    # Check if directory trees have the same number of directories
    if( $FirstDirectoryDirectoryCount -ne $SecondDirectoryDirectoryCount )
    {
        return $false
    }

    # Get the count of files on both subtrees
    $FirstDirectoryFileCount = (Get-ChildItem $FirstDirectory -Force -File | Measure-Object).Count
    $SecondDirectoryFileCount = (Get-ChildItem $SecondDirectory -Force -File | Measure-Object).Count

    # Check if directory trees have the same number of files
    if( $FirstDirectoryFileCount -ne $SecondDirectoryFileCount )
    {
        return $false
    }

    # Get the list of directories for both folders
    $FirstDirectoryDirectoryList = Get-ChildItem -Path $FirstDirectory -Force -Recurse -Directory
    $SecondDirectoryDirectoryList = Get-ChildItem -Path $SecondDirectory -Force -Recurse -Directory

    # Test if directories in the first folder exist in the second
    ForEach($d in $FirstDirectoryDirectoryList )
    {
        $path = $d.fullname
        $path = $path.Replace($firstDirectory, $secondDirectory)
        if( (Test-Path $path) -eq $false)
        {
            return $false
        }
    }

    # Test if directories in the second folder exist in the first
    ForEach($d in $SecondDirectoryDirectoryList )
    {
        $path = $d.fullname
        $path = $path.Replace($secondDirectory,$firstDirectory)
        if( (Test-Path $path) -eq $false)
        {
            return $false
        }

    }

    # Get the list of files for both directories
    $FirstDirectoryFileList = Get-ChildItem -Path $FirstDirectory -Force -Recurse -File
    $SecondDirectoryFileList = Get-ChildItem -Path $SecondDirectory -Force -Recurse -File

    # Check if every file in the first directory exists in the second
    ForEach($d in $FirstDirectoryFileList )
    {
        $path = $d.fullname
        $path = $path.Replace($firstDirectory, $secondDirectory)
        if( (Test-Path $path) -eq $false)
        {
            return $false
        }
    }

    # Check if every file in the second directory exists in the first
    ForEach($d in $SecondDirectoryFileList )
    {
        $path = $d.fullname
        $path = $path.Replace($secondDirectory,$firstDirectory)
        if( (Test-Path $path) -eq $false)
        {
            return $false
        }
    }

    # Check if the files have the same size first and then check their sum
    ForEach($d in $FirstDirectoryFileList )
    {
        $path = $d.fullname
        $path = $path.Replace($firstDirectory, $secondDirectory)

        if( $d.Length -ne (Get-Item -Path $path).Length)
        {
            return $false
        }

        $firsthash = _Get-MD5 $d.FullName
        $secondhash = _Get-MD5 $path

        if( $firsthash -ne $secondhash)
        {
            return $false
        }
    }

    return $true
}
#endregion

#region Compare-Directory
function Compare-Directory
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true, position=0, ValueFromPipelineByPropertyName=$true, HelpMessage="The reference directory to compare one or more difference directories to.")]
        [System.IO.DirectoryInfo]$ReferenceDirectory,
 
        [Parameter(Mandatory=$true, position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="One or more directories to compare to the reference directory.")]
        [System.IO.DirectoryInfo[]]$DifferenceDirectory,
 
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Recurse the directories")]
        [switch]$Recurse,
 
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Files to exclude from the comparison")]
        [String[]]$ExcludeFile,
 
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Directories to exclude from the comparison")]
        [String[]]$ExcludeDirectory,
 
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Displays only the characteristics of compared objects that are equal.")]
        [switch]$ExcludeDifferent,
        
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Displays characteristics of files that are equal. By default, only characteristics that differ between the reference and difference files are displayed.")]
        [switch]$IncludeEqual,
        
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Passes the objects that differed to the pipeline.")]
        [switch]$PassThru
    )
 
 
    begin
    {
        $ReferenceDirectory = (Resolve-Path $ReferenceDirectory).Path
        for( $i=0; $i -lt $DifferenceDirectory.Count; $i++)
        {
            $DifferenceDirectory[$i] = (Resolve-Path $DifferenceDirectory[$i]).Path
        }

        function Get-MD5
        { 
            [CmdletBinding(SupportsShouldProcess=$false)]
            param
            (
                [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="file(s) to create hash for")]
                [Alias("File", "Path", "PSPath", "String")]
                [ValidateNotNull()]
                $InputObject
            )
 
            begin
            {
                $cryptoServiceProvider    = [System.Security.Cryptography.MD5CryptoServiceProvider]
                $hashAlgorithm             = new-object $cryptoServiceProvider 
            }
            
            process
            {
                $hashByteArray = ""
                
                $item = Get-Item $InputObject -ErrorAction SilentlyContinue
                if ($item -is [System.IO.DirectoryInfo])    { throw "Cannot create hash for directory" }
                if ($item)                                     { $InputObject = $item }
                
                if ($InputObject -is [System.IO.FileInfo])
                {
                    $stream         = $null; 
                    $hashByteArray    = $null
 
                    try
                    {
                        $stream                 = $InputObject.OpenRead(); 
                        $hashByteArray             = $hashAlgorithm.ComputeHash($stream); 
                    }
                    finally
                    {
                        if ($stream -ne $null)
                        {
                            $stream.Close(); 
                        }
                    }
                }
                else
                {
                    $utf8             = new-object -TypeName "System.Text.UTF8Encoding"
                    $hashByteArray     = $hashAlgorithm.ComputeHash($utf8.GetBytes($InputObject.ToString())); 
                }
 
                Write-Output ([BitConverter]::ToString($hashByteArray)).Replace("-","")
            }
        } 
 
        function Get-Files
        {
            [CmdletBinding(SupportsShouldProcess=$false)]
            param
            (
                [string]$DirectoryPath,
                [String[]]$ExcludeFile,
                [String[]]$ExcludeDirectory,
                [switch]$Recurse
            )
        
            $relativeBasenameIndex = $DirectoryPath.ToString().Length
 
            # Get the files from the first deploypath
            # and ADD the MD5 hash for the file as a property
            # and ADD a filepath relative to the deploypath as a property
            Get-ChildItem -Path $DirectoryPath -Exclude $ExcludeFile -Recurse:$Recurse | foreach { 
                $hash = ""
                if (!$_.PSIsContainer) { $hash = Get-MD5 $_    }
 
                # Added two new properties to the DirectoryInfo/FileInfo objects
                $item = $_ |
                    Add-Member -Name "MD5Hash" -MemberType NoteProperty -Value $hash -PassThru |
                    Add-Member -Name "RelativeBaseName" -MemberType NoteProperty -Value ($_.FullName.Substring($relativeBasenameIndex)) -PassThru
                
                # Test for directories and files that need to be excluded because of ExcludeDirectory
                if ($item.PSIsContainer) { $item.RelativeBaseName += "\" }
                if ($ExcludeDirectory | where { $item.RelativeBaseName -like "\$_\*" })
                {    
                    Write-Verbose "Ignore item `"$($item.Fullname)`""
                }
                else
                {
                    Write-Verbose "Adding `"$($item.Fullname)`" to result set"
                    Write-Output $item 
                }
            }
        }
 
        $referenceDirectoryFiles = Get-Files -DirectoryPath $referenceDirectory -ExcludeFile $ExcludeFile -ExcludeDirectory $ExcludeDirectory -Recurse:$Recurse
    }
 
    process
    {
        if ($DifferenceDirectory -and $referenceDirectoryFiles)
        {
            foreach($nextPath in $DifferenceDirectory)
            {
                $nextDifferenceFiles = Get-Files -DirectoryPath $nextpath -ExcludeFile $ExcludeFile -ExcludeDirectory $ExcludeDirectory -Recurse:$Recurse
                            
                ###################################################
                # Compare the contents of the two file/directory arrays and return the results
                $results = @(Compare-Object -ReferenceObject $referenceDirectoryFiles -DifferenceObject $nextDifferenceFiles -ExcludeDifferent:$ExcludeDifferent -IncludeEqual:$IncludeEqual -PassThru:$PassThru -Property RelativeBaseName, MD5Hash)
                
                if (!$PassThru)
                {
                    foreach ($result in $results)
                    {
                        $path         = $ReferenceDirectory
                        $pathFiles    = $referenceDirectoryFiles
                        if ($result.SideIndicator -eq "=>")
                        {
                            $path         = $nextPath
                            $pathFiles    = $nextDifferenceFiles
                        }
                    
                        # Find the original item in the files array
                        $itemPath = (Join-Path $path $result.RelativeBaseName).ToString().TrimEnd('\')
                        $item = $pathFiles | where { $_.fullName -eq $itemPath }
 
                        $result | Add-Member -Name "Item" -MemberType NoteProperty -Value $item
                    }
                }
                
                Write-Output $results
            }
        }
    }
 
 
    <#
        .SYNOPSIS
            Compares a reference directory with one or more difference directories.
  
        .DESCRIPTION
            Compare-Directory compares a reference directory with one ore more difference
            directories. Files and directories are compared both on filename and contents
            using a MD5hash.
             
            Internally, Compare-Object is used to compare the directories. The behavior
            and results of Compare-Directory is similar to Compare-Object.
  
        .PARAMETER ReferenceDirectory
            The reference directory to compare one or more difference directories to.
  
        .PARAMETER DifferenceDirectory
            One or more directories to compare to the reference directory.
  
        .PARAMETER Recurse
            Include subdirectories in the comparison.
             
        .PARAMETER ExcludeFile
            File names to exclude from the comparison.
  
        .PARAMETER ExcludeDirectory
            Directory names to exclude from the comparison. Directory names are
            relative to the Reference of Difference Directory path
  
        .PARAMETER ExcludeDifferent
            Displays only the characteristics of compared files that are equal.
             
        .PARAMETER IncludeEqual
            Displays characteristics of files that are equal. By default, only
            characteristics that differ between the reference and difference files
            are displayed.
  
        .PARAMETER PassThru
            Passes the objects that differed to the pipeline. By default, this
            cmdlet does not generate any output.
  
        .EXAMPLE
            Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse
             
            Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config"
            Only differences are shown. Results:
             
            RelativeBaseName MD5Hash SideIndicator Item
            ---------------- ------- ------------- ----
            bin\site.dll 87A1E6006C2655252042F16CBD7FB41B => D:\TEMP\CompareTest\path2\bin\site.dll
            index.html 02BB8A33E1094E547CA41B9E171A267B => D:\TEMP\CompareTest\path2\index.html
            index.html 20EE266D1B23BCA649FEC8385E5DA09D <= D:\TEMP\CompareTest\path1\index.html
            web_2.config 5E6B13B107ED7A921AEBF17F4F8FE7AF <= D:\TEMP\CompareTest\path1\web_2.config
            bin\site.dll 87A1E6006C2655252042F16CBD7FB41B => D:\TEMP\CompareTest\path2\bin\site.dll
            index.html 02BB8A33E1094E547CA41B9E171A267B => D:\TEMP\CompareTest\path2\index.html
            index.html 20EE266D1B23BCA649FEC8385E5DA09D <= D:\TEMP\CompareTest\path1\index.html
            web_2.config 5E6B13B107ED7A921AEBF17F4F8FE7AF <= D:\TEMP\CompareTest\path1\web_2.config
  
        .EXAMPLE
            Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse -IncludeEqual
             
            Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config".
            Results include the items that are equal:
             
            RelativeBaseName MD5Hash SideIndicator Item
            ---------------- ------- ------------- ----
            bin == D:\TEMP\CompareTest\path1\bin
            bin\site2.dll 98B68D681A8D40FA943D90588E94D1A9 == D:\TEMP\CompareTest\path1\bin\site2.dll
            bin\site3.dll 9408C4B29F82260CBBA528342CBAA80F == D:\TEMP\CompareTest\path1\bin\site3.dll
            bin\site4.dll 0616E1FBE12D468F611F07768D70C2EE == D:\TEMP\CompareTest\path1\bin\site4.dll
            ...
            bin\site8.dll 87A1E6006C2655252042F16CBD7FB41B => D:\TEMP\CompareTest\path2\bin\site8.dll
            index.html 02BB8A33E1094E547CA41B9E171A267B => D:\TEMP\CompareTest\path2\index.html
            index.html 20EE266D1B23BCA649FEC8385E5DA09D <= D:\TEMP\CompareTest\path1\index.html
            web_2.config 5E6B13B107ED7A921AEBF17F4F8FE7AF <= D:\TEMP\CompareTest\path1\web_2.config
  
        .EXAMPLE
            Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse -ExcludeDifference
             
            Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config".
            Results only include the files that are equal; different files are excluded from the results.
             
        .EXAMPLE
            Compare-Directory -reference "D:\TEMP\CompareTest\path1" -difference "D:\TEMP\CompareTest\path2" -ExcludeFile "web.config" -recurse -Passthru
             
            Compares directories "D:\TEMP\CompareTest\path1" and "D:\TEMP\CompareTest\path2" recursively, excluding "web.config" and returns NO comparison
            results, but the different files themselves!
             
            FullName
            --------
            D:\TEMP\CompareTest\path2\bin\site3.dll
            D:\TEMP\CompareTest\path2\index.html
            D:\TEMP\CompareTest\path1\index.html
            D:\TEMP\CompareTest\path1\web_2.config
  
        .LINK
            Compare-Object
    #>

}
#endregion

#region Eject-Drive
Function Eject-Drive()
{
    <#
    .Synopsis
    Ejects a USB drive.
 
    .Description
    This function ejects a USB drive.
 
    .Parameter Drive
    The drive to eject.
     
    .Example
    Eject-Drive -Drive f:
    #>
 

    Param(
        [Parameter(Position=0,Mandatory=$true)] 
        [string]$Drive
        )

    $driveEject = New-Object -comObject Shell.Application
    $driveEject.Namespace(17).ParseName($Drive).InvokeVerb("Eject")
}
#endregion

#region Shred-File
<# Replaced by binary
function Shred-File
{
    <#
    .Synopsis
    Safely deletes the contents of a file.
 
    .Description
    Safely delete the contents of a file.
 
    .Parameter Path
    The file to process. Either piped from Get-ChildItem or as a string
     
    .Parameter Count
    The number of times to erase the file
 
    .Parameter Remove
    Remove the file after the process is finished.
 
    .Example
    Shred-File .\testfile.txt -Remove
    #>
 
<# Replaced by binary
 
    [CmdletBinding(
        SupportsShouldProcess=$False,
        SupportsTransactions=$False,
        ConfirmImpact="Low",
        DefaultParameterSetName="")]
 
    param(
        [Parameter(Position=0,Mandatory=$true)]
        [String] $Path,
        [Parameter(Position=1,Mandatory=$false)]
        $Count=1,
        [switch]$Remove
    )
    BEGIN
    {
    }
  
    PROCESS
    {
        # Test if the file exists.
        if( (Resolve-Path $Path -ErrorAction SilentlyContinue) -eq $null )
        {
            Write-Error "File does not exist."
            return
        }
 
        # Get full path
        $p = (Resolve-Path $Path).Path
 
        # Shred file many times
        for($i=0; $i -lt $Count; $i++)
        {
            # Get the size of the file in bytes
            $finfo = [io.fileinfo] $p
            $size = $finfo.Length
 
    # # Write zeros to file
    # $char = '0'
    # $sw = new-object System.IO.StreamWriter $Path
 
    # #TODO: use floor function here
    # $size = $size/2 - 1
    # for( $j=0; $j -lt $size; $j++)
    # {
    # $sw.Write($byte)
    # }
 
    # # Save the changes
    # $sw.Close()
 
         
            [Byte[]]$out=@();
            0..$size | %{$out += Get-Random -Minimum 0 -Maximum 255};
            [System.IO.File]::WriteAllBytes($p,$out)
        }
 
        # Check if the remove switch is set
        if( $Remove )
        {
            Remove-Item -Force -Path $p
        }
    }
 
    END
    {
    }
}
Replaced by binary #>

#endregion

#region Compare-DirectoryTree
Function Compare-DirectoryTree
{
    <#
    .SYNOPSIS
      Compares two directories.
 
    .Description
      This function compares two directories. If an item exists on both locations it's status will be marked with a "-".
      If the item is missing from the Difference location it will be marked with a "<" and with a ">" if it is missing from the Reference location.
      Items with status "!" are files with the same name on the same directory on both locations with difference checksum values.
      A status value of "?" means that the item is a file in one location and a folder in the other.
     
    .Parameter ReferencePath
      This is the path of the first directory
 
    .Parameter DifferencePath
      This is the path of the second directory
 
    .Parameter Recurse
      Use this to recursively compare the directories
     
    .Parameter PerformChecksum
      Use this to perform checksum check for files on same directories with the same name
     
    .EXAMPLE
     Compare-DirectoryTree -ReferencePath .\dir1 -DifferencePath .\dir2
     This command will compare only the contents of the directory dir1 to the contents of the directory dir2.
 
     Compare-DirectoryTree -ReferencePath .\dir1 -DifferencePath .\dir2 -Recurse -PerformChecksum
     This command will compare the contents of the directory dir1 to the contents of the directory dir2.
     If there are subdirectories, they will also be compared recursively.
     Moreover, if a file exists on both directories, a checksum test will be performed.
 
    #>


    Param(
        [string]$ReferencePath,
        [string]$DifferencePath,
        [switch]$PerformChecksum,
        [switch]$Recurse
        )

    Function _Compare-DirectoryTree
    {
        Param(
            [string]$ReferencePath,
            [string]$DifferencePath,
            [string]$referenceroot,
            [string]$differenceroot,
            [switch]$PerformChecksum,
            [switch]$Recurse
            )

        # The array to hold the results
        $results = @()

        # TODO: Check if both paths exist

        # Get full paths
        $fullreferencepath = Resolve-Path $ReferencePath
        $fulldifferencepath = Resolve-Path $DifferencePath

        # Get files and folders of each directory
        $files1 = Get-ChildItem -Path $fullreferencepath -Force
        $files2 = Get-ChildItem -Path $fulldifferencepath -Force

        # Loop through files and directories of the reference directory
        foreach($f1 in $files1)
        {
            # Form the relevant path that should exist on the difference directory
            $f1fullpath = $f1.FullName
            $testpath = $f1fullpath.Replace($fullreferencepath,$fulldifferencepath)

            # Test if file/directory exists on difference directory
            if(Test-Path $testpath)
            {
                # Check if the name is file compared to file or directory compared to directory
                if( (Get-Item $f1fullpath).PSIsContainer -eq (Get-Item $testpath).PSIsContainer)
                {
                    # Add file / folder marked as existing on both locations
                    $tmp = New-Object PSObject
                    $tmp | Add-Member -MemberType NoteProperty -Name "FullPath" -Value $f1fullpath
                    $tmp | Add-Member -MemberType NoteProperty -Name "Path" -Value $f1fullpath.Substring($referenceroot.Length + 1)

                    # Check if we have to make a checksum check
                    if( $PerformChecksum )
                    {
                        if( -Not ( (Get-Item $f1fullpath).PSIsContainer) )
                        {
                            if( (Get-FileHash -Path $f1fullpath -Algorithm MD5).Hash -eq (Get-FileHash -Path $testpath -Algorithm MD5).Hash )
                            {
                                $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value "-"
                            }
                            else
                            {
                                $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value "!"
                            }
                        }
                        else
                        {
                            $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value "-"
                        }

                    }
                    else
                    {
                        $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value "-"
                    }
                    $results += $tmp

                    # If we are comparing directories, recursively compare them
                    if( $Recurse )
                    {
                        if( ( (Get-Item -Path $f1fullpath) -is [System.IO.DirectoryInfo]) -and ( (Get-Item -Path $f1fullpath) -is [System.IO.DirectoryInfo]) )
                        {
                            if( $PerformChecksum )
                            {
                                $results += _Compare-DirectoryTree -ReferencePath $f1fullpath -DifferencePath $testpath -referenceroot $referenceroot -differenceroot $differenceroot -PerformChecksum -Recurse
                            }
                            else
                            {
                                $results += _Compare-DirectoryTree -ReferencePath $f1fullpath -DifferencePath $testpath -referenceroot $referenceroot -differenceroot $differenceroot -Recurse
                            }
                        }
                    }
                }
                else
                {
                    # If the name is file on one location and directory on the other mark as different
                    $tmp = New-Object PSObject
                    $tmp | Add-Member -MemberType NoteProperty -Name "FullPath" -Value $f1fullpath
                    $tmp | Add-Member -MemberType NoteProperty -Name "Path" -Value $f1fullpath.Substring($referenceroot.Length + 1)
                    $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value "?"
                    $results += $tmp
                }
            }
            else
            {
                # The file / directory was not found on the second location
                $tmp = New-Object PSObject
                $tmp | Add-Member -MemberType NoteProperty -Name "FullPath" -Value $f1fullpath
                $tmp | Add-Member -MemberType NoteProperty -Name "Path" -Value $f1fullpath.Substring($referenceroot.Length + 1)
                $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value "<"
                $results += $tmp
            }
        }

        # Loop through files / folders in the second location
        foreach($f2 in $files2)
        {
            $f2fullpath = $f2.FullName
            $testpath = $f2fullpath.Replace($fulldifferencepath,$fullreferencepath)
            if(Test-Path $testpath)
            {
            }
            else
            {
                $tmp = New-Object PSObject
                $tmp | Add-Member -MemberType NoteProperty -Name "FullPath" -Value $f2fullpath
                $tmp | Add-Member -MemberType NoteProperty -Name "Path" -Value $f2fullpath.Substring($differenceroot.Length + 1)
                $tmp | Add-Member -MemberType NoteProperty -Name "Status" -Value ">"
                $results += $tmp
            }
        }

        return $results

    }

    # Test paths
    if( -Not (Test-Path $ReferencePath) )
    {
        Write-Error "Reference path not found."
        return
    }
    if( -Not (Test-Path $DifferencePath) )
    {
        Write-Error "Difference path not found."
        return
    }

    # Start processing
    if( $PerformChecksum )
    {
        if( $Recurse )
        {
            return _Compare-DirectoryTree -ReferencePath (Resolve-Path $ReferencePath) -DifferencePath (Resolve-Path $DifferencePath) -referenceroot (Resolve-Path $ReferencePath) -differenceroot (Resolve-Path $DifferencePath) -PerformChecksum -Recurse
        }
        else
        {
            return _Compare-DirectoryTree -ReferencePath (Resolve-Path $ReferencePath) -DifferencePath (Resolve-Path $DifferencePath) -referenceroot (Resolve-Path $ReferencePath) -differenceroot (Resolve-Path $DifferencePath) -PerformChecksum
        }
    }
    else
    {
        if( $Recurse )
        {
            return _Compare-DirectoryTree -ReferencePath (Resolve-Path $ReferencePath) -DifferencePath (Resolve-Path $DifferencePath) -referenceroot (Resolve-Path $ReferencePath) -differenceroot (Resolve-Path $DifferencePath) -Recurse
        }
        else
        {
            return _Compare-DirectoryTree -ReferencePath (Resolve-Path $ReferencePath) -DifferencePath (Resolve-Path $DifferencePath) -referenceroot (Resolve-Path $ReferencePath) -differenceroot (Resolve-Path $DifferencePath)
        }
    }

}
#endregion

#region Resolve-NonExistentPath
Function Resolve-NonExistentPath
{
    <#
    .SYNOPSIS
        Get the full path using a relative path of a file or folder that does not exist.
 
    .DESCRIPTION
        The Resolve-NonExistentPath cmdlet will return the full path to a file or folder that does not exist.
 
    .PARAMETER Path
        The path to resolve.
 
    .EXAMPLE
        Resolve-NonExistentPath -Path test.txt
 
        This will return the full path to the test.txt path
    #>


    Param
    (
        [string]$Path
    )

    $fullpath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)

    $obj = New-Object psobject
    $obj | Add-Member -MemberType NoteProperty -Name "Name" -Value $Path
    $obj | Add-Member -MemberType NoteProperty -Name "FullName" -Value $fullpath

    $obj
}
#endregion

#region REmove-EmptyDirectories
Function Remove-EmptyDirectories
{
    <#
    .SYNOPSIS
        Remove all empty directories in a folder tree.
 
    .DESCRIPTION
        The Remove-EmptyDirectories cmdlet will remove all the empty directories under a path recursively. If the directory Path ends up empty it will also be removed.
 
    .PARAMETER Path
        The path to examine
 
    .EXAMPLE
        Remove-EmptyDirectories -Path MyDir
 
        This will remove all the empty directories under MyDir recursively. If the MyDir directory ends up empty it will be removed too.
    #>


    Param
    (
        [string]$Path
    )

    # Get the full path to the directory
    $fullpath = (Resolve-Path $Path)

    # Get the list of file in the directory
    $files = Get-ChildItem -Path $fullpath -Force -file

    # Get the list of folders in the directory
    $folders = Get-ChildItem -Path $fullpath -Force -Directory

    # Loop through folders and recursively check subdirectories
    foreach($f in $folders)
    {
        Remove-EmptyDirectories $f.FullName
    }

    # Get the folders again becuase the recursive call would remove the empty subfolders
    $folders = Get-ChildItem -Path $fullpath -Force -Directory

    # If there are not files or folders, remove the folder
    if( ($files.count -eq 0) -and ($folders.count -eq 0) )
    {
        Remove-Item $fullpath
    }
}
#endregion

#region Get-FileMetadata
function Get-FileMetadata
{
    #region Parameters
    [CmdletBinding(SupportsShouldProcess=$true, 
                   PositionalBinding=$false,
                   ConfirmImpact='Low')]
    [Alias()]
    [OutputType([String])]
    Param
    (
        # The path to the file
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $Path
    )
    #endregion

    #region Begin
    Begin
    {
        # Create a shell object
        $Shell = New-Object -ComObject Shell.Application 
    }

    #region Process
    Process
    {
        foreach($p in $Path)
        {
            Write-Verbose "Getting metadata of file $p."

            # Get the full path to the file
            try
            {
                $fullPath = (Resolve-Path -Path $p -ErrorAction Stop).Path
            }
            catch
            {
                Write-Error $_.exception.message
                continue
            }

            # Create the objects
            try
            {
                $folder = $Shell.NameSpace([System.IO.Path]::GetDirectoryName($fullPath))
                $folderItem = $folder.ParseName([System.IO.Path]::GetFileName($fullPath))
            }
            catch
            {
                Write-Error "Failed to get the metadata of the file."
            }

            # Create the hashtable for the properties
            $properties = [ordered]@{}

            # Get each property
            for ($i = 0; $i -le [int16]::MaxValue; $i++)
            {
                [string]$header = $folder.GetDetailsOf($null, $i)
                if([String]::IsNullOrEmpty($header))
                {
                    break;
                }

                try
                {
                    $detail = $s = [Regex]::Replace($folder.GetDetailsOf($folderItem, $i), '\p{C}+', [string]::Empty)
                    $properties.Add($header, $detail)
                }
                catch{}
            }

            # Create a custom object
            New-Object -TypeName PSObject -Property $properties
        }
    }
    #endregion

    #region End
    End
    {
    }
    #endregion
}
#endregion

#region Exports
Export-ModuleMember -Function Get-DuplicateFiles
Export-ModuleMember -Function Test-DuplicateFile
Export-ModuleMember -Function Test-DuplicateDirectory
Export-ModuleMember -Function Compare-Directory
Export-ModuleMember -Function Eject-Drive
Export-ModuleMember -Function Shred-File
Export-ModuleMember -Function Compare-DirectoryTree
Export-ModuleMember -Function Resolve-NonExistentPath
Export-ModuleMember -Function Remove-EmptyDirectories
Export-ModuleMember -Function Get-FileMetadata
#endregion