Search code examples
powershellcsvexport-to-csv

unable to append error messages to csv with powershell export-csv


I have written the following sample script that lets me collect information for all servers in the environment. However, i do not have access to all servers and sometimes i get error that i want to catch and store in the result.csv file.


$Servers = Get-Content .\servers.txt
foreach ($Server in $Servers){

try {
    Get-CimInstance Win32_OperatingSystem -ComputerName $server -ErrorAction Stop | Select-Object CSName, Caption, Version, OSArchitecture, InstallDate, LastBootUpTime | Export-Csv -append .\result.csv

} catch {

   $Error[0].Exception | Export-csv -Append .\resulttest.csv

}
}

Normally the script works but when i try to save the errors i get the message:

Export-csv : Cannot append CSV content to the following file: .\resulttest.csv. The appended object does not have a property that corresponds to the following column: CSName. To proceed with mismatched properties, add the -Force switch and retry. At C:\temp\script\serverdata.ps1:10 char:26 + $Error[0].Exception | Export-csv -Append .\resulttest.csv + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (CSName:String) [Export-Csv], InvalidOperationException + FullyQual

Any ideas on how to go around this?


Solution

  • You might try this:

    $Servers = Get-Content .\servers.txt
    
    $Servers | ForEach-Object {
        $server = $_
        try {
            Get-CimInstance Win32_OperatingSystem -ComputerName $server -ErrorAction Stop | 
            Select-Object CSName, Caption, Version, OSArchitecture, InstallDate, LastBootUpTime, @{Name = 'Result'; Expression = {'OK'}}
        } 
        catch {
            # output an object with the same properties.
            "" | Select-Object @{Name = 'CSName'; Expression = {$server}}, 
                               Caption, Version, OSArchitecture, InstallDate, LastBootUpTime, 
                               @{Name = 'Result'; Expression = {'ERROR: {0}' -f $Error[0].Exception.Message}}
        }
    } | Export-Csv .\result.csv -NoTypeInformation