Search code examples
powershellcsv

Exporting CSV results to two different paths


I have a PowerShell script that I would like to export to two different CSV files. One of them also includes an additional parameter to append. I've tried this and it does create a second CSV, but it's blank. Can someone please help?

Get-RemoteProgram -ComputerName (Get-Content -Path C:\PowerShell\complist.txt) -ExcludeProgram (Get-Content -Path C:\PowerShell\applist.txt) | Where-Object {($_.ProgramName -notmatch 'KB\d+|Microsoft .NET|Microsoft Visual|Intel|Windows Driver Package')} | sort-object -property computer,programName | export-csv -path C:\PowerShell\output.csv -NoTypeInformation | export-csv -path C:\PowerShell\outputappend.csv -NoTypeInformation -Append

Solution

  • Your code boils down to this:

    Get-RemoteProgram ... | Export-Csv ... | Export-Csv ...
    

    You're piping the output from the first Export-Csv into the second, but the documentation says of Export-Csv

    Output

    This cmdlet returns no output.

    (see https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-7.4#outputs)

    So the second Export-Csv is equivalent to:

    $null | Export-Csv ...
    

    What you need to do is capture the csv data into a temporary variable and then pipe that into two separate calls to Export-Csv:

    # build the data to export to csv
    $data = Get-RemoteProgram ...
    
    # export to file 1
    $data | Export-Csv ...
    
    # export to file 2
    $data | Export-Csv ...