Photo by Fallon Michael / Unsplash

Powershell - Test if AD object exists

Nov 6, 2018

Be careful about the 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 or Get-ADGroup.

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

try
{
    $ADUser = Get-ADUser -Identity $user -ErrorAction Stop
}
catch
{
     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 doesn’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 an array

Cast the returned value in an array with the usage of @()  and check the property .Countproperty. 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 boolean

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

$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

Tags

Bastien Perez

Freelance Microsoft 365 - Active Directory - Modern Workplace