Thursday, 10 November 2016

Check if AD user exists with PowerShell

In this article I am going write powershell commands to check if an Active Directory user exists or not with the AD Powershell cmdlet Get-ADUser. First run the below command to import the Active Directory module.
Import-Module ActiveDirectory
The below command checks if the given user account exists in AD or not. You can identify a user by its distinguished name (DN), GUID, SID,SamAccountName or Name.
$Name = "kevin"
$User = $(try {Get-ADUser $Name} catch {$null})
If ($User -ne $Null) { 
"User exists in AD" 
} Else {
"User not found in AD"}
You need to use try-catch block to skip error when user not found, otherwise you will receive the error message 'Get-ADUser : Cannot find an object with identity'.

Find if multiple AD users are exists or not

We can set list of user names as array object and enumerate the users to find user account in AD.
$users = @("kevin","smith","nick")
foreach ($user in $users) {
$userobj = $(try {Get-ADUser $user} catch {$Null})
If ($userobj -ne $Null) {
    Write-Host "$user already exists" -foregroundcolor "green"
} else {
    Write-Host "$user not found " -foregroundcolor "red"
}}

Advertisements
Advertisements

No comments:

Post a Comment