无法使用 powershell export-csv 将错误消息附加到 csv

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

我编写了以下示例脚本,可以让我收集环境中所有服务器的信息。但是,我无法访问所有服务器,有时我会收到错误消息,我想将其捕获并存储在 result.csv 文件中。


$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

}
}

通常情况下,脚本可以正常工作,但是当我尝试保存错误时,我收到消息:

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

关于如何解决这个问题有什么想法吗?

你可以试试这个:

$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