How to write exception details to csv

0
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

I am getting errors like the below which I would like to have placed into the CSV as well and with txt it is down with PC name:

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
powershell
wmi
export-to-csv
asked on Stack Overflow Mar 3, 2017 by Jeremy Stump • edited Mar 7, 2017 by Clijsters

1 Answer

4

Sounds like you need a Try/Catch in a ForEach loop. I think something like this should do it for you:

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
answered on Stack Overflow Mar 3, 2017 by TheMadTechnician

User contributions licensed under CC BY-SA 3.0