Error when AD object not found

This one popes up quite frequently

If you attempt to access an Active Directory object that doesn’t exist you get an error.

£> Get-ADUser Richardp
Get-ADUser : Cannot find an object with identity: ‘Richardp’ under: ‘DC=Manticore,DC=org’.
At line:1 char:1
+ Get-ADUser Richardp
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Richardp:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
   icrosoft.ActiveDirectory.Management.Commands.GetADUser

Just using the Erroraction option isn’t going to help

£> Get-ADUser Richardp -ErrorAction SilentlyContinue
Get-ADUser : Cannot find an object with identity: ‘Richardp’ under: ‘DC=Manticore,DC=org’.
At line:1 char:1
+ Get-ADUser Richardp -ErrorAction SilentlyContinue
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Richardp:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
   icrosoft.ActiveDirectory.Management.Commands.GetADUser

You could do something like this

$ErrorActionPreference = ‘SilentlyContinue’
Get-ADUser Richardp
$ErrorActionPreference = $pref

But a better approach is to use a try-catch block to solve the problem

£> try {
Get-ADUser Richardp -ErrorAction Stop
}
catch {
Write-Warning “User Not Found”
}
WARNING: User Not Found

Instead of issuing the warning perform some other action as appropriate

Advertisements
This entry was posted in PowerShell and Active Directory. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s