powershellactive-directorysccm

Appending empty line on error into output grid using Powershell


Afternoon all, So i have a script that is working really well but with one caveat. If there is a device listed in the computers.txt file that no longer exists in AD, the script will error and that machine will be missing from the output grid.

This makes it quite annoying when i am trying to get it to match up in a CSV as it has missing lines.

cls Get-Content -Path "$home\Desktop\computers.txt" | ForEach-Object {Get-ADComputer $_ -Properties Name, CanonicalName, Enabled, IPv4Address, OperatingSystem, OperatingSystemVersion, LastLogonTimeStamp, Description | select-object Name, CanonicalName, Enabled, IPv4Address, OperatingSystem, OperatingSystemVersion, @{Name="LastLogonTime"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('dd-MM-yyy_hh:mm:ss')}}, Description} | Out-GridView

I tried adding a try and catch however as this is non terminating i don't think this will work. Is anyone able to assist with getting this to output all the machines as normal and if it errors (machine x missing) it will still add a line and just say error or something?


Solution

  • Several ways to do this, but I find the easiest is to user Try...Catch to enter a dummy value for the item not found:

    Get-Content -Path "$home\Desktop\computers.txt" | ForEach-Object {
        Try {
            Get-ADComputer $_ -Properties CanonicalName, IPv4Address, OperatingSystem, OperatingSystemVersion, LastLogonTimeStamp, Description -ErrorAction Stop | Select-Object Name, CanonicalName, Enabled, IPv4Address, OperatingSystem, OperatingSystemVersion, @{Name="LastLogonTime"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('dd-MM-yyy_hh:mm:ss')}}, Description
        }
        Catch {
            [pscustomobject]@{Name=$_;CanonicalName='';Enabled='';IPv4Address='';OperatingSystem='';OperatingSystemVersion='';LastLogonTime='';Description=''}
        }
    } |  Out-GridView