Tag Archives: Get-AdGroup

PowerShell–Verify AD Principal

I recently needed to add a function which would verify if an Active Directory principal exists. I also did not know if the principal is a Group or a User.

My first attempt was to use the straight forward cmdlets Get-AdGroup and Get-AdUser in an “If” statement block (i. e. If Group is not found then try User).  My script looked like this:

If(!(Get-ADGroup -Identity $Principal)) {
    If(!(Get-ADUser -Identity $Principal)) {
        Throw "AD principal $principal was not found"
Write-Host "AD principal $principal found."

I found out immediately that when Get-AdGroup gets an error it writes an error message and the entire script block (everything under the first IF and including the second IF) gets ignored and the following statement “ Write-Host” gets executed. Because a not found condition is not a terminating error, adding –ErrorAction SilentlyContinue has no effect.

What I ended up doing is adding an -ErrorAction Stop to each cmdlet. That way I could use Try{} Catch{} to trap it at Get-AdGroup and use the trap to then check if the principal is a user using Get-AdUser. The final code looks like this:

Try {Get-ADGroup -Identity $Principal -ErrorAction Stop} 
    Catch { Try {Get-ADUser -Identity $Principal -ErrorAction Stop} Catch { Throw $_ }}

Write-Host "AD principal $principal found."