Check user exist in AD with powershell

avanis
Kilo Contributor

I have a condition to check if user exist in AD so that while rehiring we do not create a new userid for the same user who has a deactivated account and reactivate the same account.

I found ways to to do that via AD activities but that uses LDAP.

I do not have LDAP and want to do the same via powershell script.

Can anyone help how to do that.

13 REPLIES 13

It would be slow as it is search the entire directory for the user. Are you getting any output?



If you want to finish it quickly you may have to search only the OU in the AD where the Users are located, likewise use:



Get-ADUser -Filter {Name -eq $users} -SearchBase "OU=UserAccounts,DC=FABRIKAM,DC=COM"


Hi Adil,



Here Name will be username, how to process this with UserID ?


As we dont want the search to happen with user name.


adilrathore
ServiceNow Employee
ServiceNow Employee

Did you try SAMAccountName


$users = $userId



if (Get-AdUser $users )


      {


        Write-host "User already exists"


      }


else {


              Write-Host "User doesn't exist in AD"


      }



Hi Adil,



Above code works well when user already exist.


But when i am entering new user which should go in else, it is not printing the message and instead giving an error.



Since i have 3 conditions to check:


user exist


user doesn't exist


faliure(else)



How can i check 2nd condition where user is new.


adilrathore
ServiceNow Employee
ServiceNow Employee

What is the error message...