How do i export results of a foreach-object with custom object in powershell

144 Views Asked by At

I can't seems to be able to export the results of the Foreach in a csv or even a txt file. It asks me for input or simply a blank file

What the code do is import two csv both with same values but with eventual difference or missing value compare them and return the results

function compare {

    #Declaring vars
    $csv3 = "C:\Users\xxxxxxxx\Desktop\file3.csv"
    $csv1 = Import-Csv -Path "C:\Users\xxxxxxxx\Desktop\file.csv"
    $csv2 = Import-Csv -Path "C:\Users\xxxxxxxx\Desktop\file2.csv"

    #Start of the main block
    echo "Running..."
    Compare-Object $csv1 $csv2 -IncludeEqual -Property Name,Size,Version,FullName,LastWriteTime |
       ForEach-Object {
            If( $R.sideindicator -ne "==" ){
                  [PSCustomObject]@{
                    Name  = ($_.Name)
                    Srv1 = ($_.FullName, $_.Size,$_.LastWriteTime, $_.Version)
                    Srv2 = ($csv2   | Select-object -Property ($_.FullName, $_.Size,$_.LastWriteTime), @{Name="Version";Expression={$_.Version -replace "",'empty'}})

                } 
            }
        }
}

This is one of the output

Name           Srv1                                                                                                 Srv2                                                                                                       
----           ----                                                                                                 ----                                                                                                       
caqs_.exe    \application\caqs_.exe,26,4469604492188,27/01/2020 17:00:23,5, 82, 254, 0 {@{\application\caqs_.exe,26,4469604492188,27/01/2020 17:00:23=; Version=}, @...

Now i want to be able to export the same return values above inside a csv, or anything that could keep this format, if i put an export-csv i either have a blank empty csv file or the console will ask me for inputobject.

1

There are 1 best solutions below

1
David On

The 'Compare-Object' cmdlet returns properties, 'InputObject','SideIndicator'. I believe the properties you are wanting to access are nested inside the 'InputObject' property. For example, instead of $_.FullName, you'll want to use $_.InputObject.FullName.

Or you could simplify the script and do something like this:

(Compare-Object $csv1 $csv2 -IncludeEqual -Property Name,Size,Version,FullName,LastWriteTime | Where-Object {$_.SideIndicator -ne "=="}).InputObject | Export-Csv $csv3 -NoTypeInformation