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
0

1 Answer 1

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
1
  • Even if there are several code styles for PoSh, I'd suggest to place spaces before curly braces.
    – Clijsters
    Mar 7, 2017 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.