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 present several ways 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 CMDlets Get-ADUser
/ Get-ADComputer
/ Get-ADGroup
/ Get-ADObject
and get the error.
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 or Windows 7 or with -Filter
For the old PowerShell version (1.0 and 2.0), the Get-AD*
CMDlets (Get-ADComputer
, Get-ADUser
, Get-ADGroup
, Get-Object
, etc. ) does not 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 .Count
property. 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 boolean 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
Clap
Comments