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 domain controller 2016/2019
On a domain controller 2016/2019, you can use the command Get-ADUser (or Get-ADComputer ,Get-ADGroup).
In case of error, an exception can be catch with try/catch :
On a domain controller 2012 R2 or older
On preivous versions (2012 R2 and older), 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:
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).