Handling Objects not Found in Active Directory

The Active Directory module for PowerShell has been around for a very long time now, and it’s even still an OG Windows PowerShell module. I noted some interesting behaviour on some recent work I wanted to share.

Let’s consider the Get-ADUser CMDlet, but this could apply to other Get-AD* type CMDlets. I had a situation recently where by I wanted to get a user object, but it may or may not exist.

$User = Get-ADUser -Identity jreacher

Nice and simple. Not being an everyday user of this module I kind of expected that if the user was not found, I’d get a null result. However I get this:

No worries, I’ll specify the ErrorAction as SilentlyContinue, that’ll do what I want. But wait, it doesn’t alter the behaviour 🤔

How odd. I really don’t want my script blowing up when a user is not found. Could we do something sneaky with the try catch block to try and supress the error perhaps?

try {
    $User = Get-ADUser -Identity jreacher
}
catch {
}

Hmmm, yes this does suppress the error, but it’s no good for handling actual errors. We need something better.

I have seen people take this approach, which in fairness does work:

try {
    $User = Get-ADUser -Identity jreacher
}
catch {
    if ($null -eq $User) {
        Write-Warning 'User not found'
    }
    else {
        Write-Error 'Something went wrong'
    }
}

Seems a bit clunky. One thing to be wary of here is that since Get-ADUser is not returning an output, null or otherwise, whatever value the $User variable was previously will still apply. You may consider setting $User to null before this block.

However there is a better way, using a typed exception. With typed exceptions we can do different things depending on what exception is thrown. Let’s take a look.

try {
    $User = Get-ADUser -Identity jreacher -ErrorAction Stop
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
    $User = $null
    Write-Warning 'User not found'
}
catch {
    Write-Error 'This went wrong.'
}

This is perfect for what I want to do. Hopefully this helps someone with their Active Directory scripting 😎

Leave a comment