FileSystem.psm1
#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 |