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" }}
Check if a user in a CSV file exists in AD
The following commands import user accounts from CSV file and check every user exists or not in AD. Consider the CSV file Users.csv which includes the column UserPrincipalName which holds the UPN of the user in each row of the CSV file.
$Result=@() Import-Csv 'C:\Users.csv' | ForEach-Object { $user = $_."UserPrincipalName" $userobj = $(try {Get-ADUser $user} catch {$Null}) If ($userobj -ne $Null) { $UserExists = $true } else { $UserExists = $false } $Result += New-Object PSObject -property @{ UserPrincipalName = $user UserExists = $UserExists } } $Result | Select UserPrincipalName,UserExists
Run the below command to export the result to CSV file.
$Result | Export-CSV "C:\ADAccountStatusReport.csv" -NoTypeInformation -Encoding UTF8
Howdy,
thank you man, launched on an AD with >15k samaccountnames. Saved many hours!!!
Happy New Year.
Really good thanks for taking the time to post this
If you want to delete homdrive or a profile drive for a non excisting user. You can read the profiledrive and then compare them to excisting users in your AD:
$users = get-childitem -Path Z:\UEMProfiles
foreach ($user in $Users) {
$userobj = $(try {Get-ADUser $user.name} catch {$Null})
If ($userobj -ne $Null) {
} else {
remove-item -path z:\uemprofiles\$user -Recurse -force
}}