Search code examples
powershellpowershell-4.0compareobject

Comparing Desktop and documents with their backup and produce an output.txt file that highlights the different folders and files between them


can someone please help me. Still new to powershell, I am comparing my documents and desktop mirror to check my backup solutions using several different codes. The one below is meant to check both the documents/desktop with its mirror folders and tell me exactly what files are 'different' between source and destination and output it into the same output.txt file (not sure if it overwrites it). When I do this for my documents alone, it works when I want try the code for my desktop it doesn't output anything at all. Any advice?

function Get-Directories ($path)
{
    $PathLength = $path.length
    Get-ChildItem $path -exclude *.pst,*.ost,*.iso,*.lnk | % {
        Add-Member -InputObject $_ -MemberType NoteProperty -Name RelativePath -Value $_.FullName.substring($PathLength+1)
        $_
    }
}

Compare-Object (Get-Directories $Folder3) (Get-Directories $Folder4) -Property RelativePath | Sort RelativePath, Name -desc | Out-File  C:\Users\desktop\output.txt

Solution

  • Judging by earlier revisions of your question, your problem wasn't that your code didn't output anything at all, but that the output had empty Name property values.

    Thus, the only thing missing from your code was Compare-Object's -PassThru switch:

    Compare-Object -PassThru (Get-Directories $Folder3) (Get-Directories $Folder4) -Property RelativePath | 
      Sort RelativePath, Name -desc | 
        Out-File C:\Users\desktop\output.txt
    

    Without -PassThru, Compare-Object outputs [pscustomobject] instances that have a .SideIndicator property (to indicate which side a difference object is exclusive to) and only the comparison properties passed to -Property.

    • That is, in your original attempt the Compare-Object output objects had only .SideIndicator and .RelativePath properties, and none of the other properties of the original [System.IO.FileInfo] instances originating from Get-ChildItem, such as .Name, .LastWriteTime, ...

    With -PassThru, the original objects are passed through, decorated with an ETS (Extended Type System) .SideIndicator property (decorated in the same way you added the .RelativePath property), accessing the .Name property later works as intended.

    Note:

    • Since Out-File then receives the full (and decorated) [System.IO.FileInfo] instances, you may want to limit what properties get written via a Select-Object call beforehand.
      Additionally you may choose a structured output format, via Export-Csv for instance, given that the formatting that Out-File applies is meant only for the human observer, not for programmatic processing.

    • $_.FullName.substring($PathLength+1) in your Get-Directories should be $_.FullName.substring($PathLength), otherwise you'll cut off the 1st char.