I’m putting this here for reference, but the idea comes from Richard Siddaway’s blog post: Error trapping when getting AD objects.
When trying to discover if a list of old VMs had AD accounts I was getting errors when the account did not exist:
Get-ADComputer : Cannot find an object with identity: 'testmigrate' under: 'DC=sub,DC=domain,DC=int'.
At line:8 char:23
+ if ($ADComputer = Get-ADComputer $hostname.Name ) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (testmigrate:ADComputer) [Get-ADComputer], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'testmigrate' under: 'DC=syd,DC=aero,DC=int'.,Microsoft.ActiveDirectory.Management.Commands
.GetADComputer
This made the output hard to read and export. I tried adding the silently continue error action to the Get-ADComputer but the error was still coming.
The solution was to use try and catch: