如何将异常详细信息写入csv

时间:2017-03-03 16:39:49

标签: powershell wmi export-to-csv

Import-Module ActiveDirectory
$computers = Get-ADComputer -Filter * -SearchBase "OU=workstations,DC=company,DC=org" |
             Select-Object -Expand Name 
$wmiObjs = Get-WmiObject -Class Win32_ComputerSystem -Property Name, Model -ComputerName $computers |
           select Name, Model |
           Export-Csv c:\temp\workstations-models.csv

我收到类似下面的错误,我希望将其放入CSV中,而使用txt,它会降低PC名称:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:3 char:12
+ $wmiObjs = Get-WmiObject -Class Win32_ComputerSystem -Property Name,  ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

1 个答案:

答案 0 :(得分:4)

听起来你需要在Try/Catch循环中ForEach。我觉得这样的事情应该适合你:

Import-Module ActiveDirectory
$computers = Get-ADComputer -Filter * -SearchBase "OU=workstations,DC=company,DC=org" |
             Select-Object -Expand Name 
$wmiobjects = ForEach($Computer in $Computers){
    Try{
        Get-WmiObject -Class Win32_ComputerSystem -Property Name, Model -ErrorAction Stop -ComputerName $Computer |
            select Name, Model
    }Catch{
        [PSCustomObject]@{'Name'=$Computer;'Model'='Offline'}
    }
}

$wmiobjects | Export-Csv c:\temp\workstations-models.csv -NoTypeInformation