PowerShell – Test if AD object exists

Lire l’article en français ici.

Be careful about th AD module

When building PowerShell scripting with Active Directory, it is often useful to check if an AD object (user, computer, group) is present or not.

First, you need to install PowerShell AD Module.

On the latest versions of PowerShell shipped with Windows Server 2016 and 2019, the inexistence of an object in the AD causes an error that can be handled with try/catch.

However, the behavior is different on older versions. The management of blocking errors in PowerShell is sometimes capricious, we could try adding -ErrorAction Stop parameter to force the stop … nice try but it does not work!

This article présents the differents way to test the existence of an user or computer or group or any AD object in an Active Directory depending on the version.

On Windows Server 2012/2012R2/2016/2019 or Windows 8/8.1/10

For PowerShell 3.0 or above, you can use the command Get-ADUser (or Get-ADComputer ,Get-ADGroup).

In case of error, an exception can be catch with try/catch :

  $ADUser = Get-ADUser -Identity $user -ErrorAction Stop
  Write-Warning "An error occured: $($_.Exception.Message)"

On Windows Server 2008/2008R2 ou Windows 7

For the old PowerShell version (1.0 and 2.0), the Get-ADUser command don’t rise execution error, so the catch part will never be executed. Of course, this behavior can be a problem.

To overcome this problem, you can use one of the methods below.

Method 1 – cast to array

Cast the returned value in an array with the usage of @() and verify the property .Count. If it equals to 0, the user exist, otherwise he is not:

if (@(Get-ADUser -Filter {SamAccountName -eq "xxx"}).Count -eq 0)
  Write-Warning -Message "User xxx does not exist."

Method 2 – cast to booléen

Cast the returned value to a boolean with the usage of [bool]. A booolean can either be TRUE or FALSE (respectively 1 or 0).

# existing account
$samAccountName = 'Administrator'
[bool] (Get-ADUser -Filter {sAMAccountName -eq 'Administrator'} # return TRUE

# nonexisting account
[bool] (Get-ADUser -Filter {sAMAccountName -eq 'toto'} # return TRUE

# Note : if a variable is use, the filter has to be different (string instead of {})
# existing account
$samAccountName = 'Administrator'
[bool] (Get-ADUser -Filter "sAMAccountName -eq '$($samAccountName)'") # return TRUE

# nonexisting account
$SamAccountName = 'toto'
[bool] (Get-ADUser -Filter "sAMAccountName -eq '$($samAccountName)'") # return FALSE

This Post Has One Comment

Leave a Reply

Close Menu