Forum Discussion
Check if user already exists
Hi there,
I'm trying to create a script which basically requires the user's input, so they'll need to enter their first name & last name and AD will check if that AD account already exists for the user or not, if it does then it would say '_____ already exists' and stops the script going any further as it's currently doing for any users whether or not they exist - below.
What's the correct commands I should be using as below so it will search AD for that user and if they don't exist it would say 'User doesn't exist' and continue with the rest of the script which then asks for the user's dept and phone number etc, as currently it's just saying all the user's already exist and stops the script, I've tried various recommended commands from other forums.
Thank you in advance
- MikeCrowleyIron Contributor
It's difficult to read your code, since the picture loads very small on my browser. Next time I suggest posting the code itself instead of screenshots.
I'm not a fan of scripts written for other people to type in. Read-host is kinda neat the first day you discover it, but I think you'll end up discovering that this approach is far too fragile.
That aside, checking to see if an account exists or not is a pretty common requirement. There are lots of ways to do it, but in general, you try to get the account in question, and if you couldn't, you know it doesn't exist! You'll need to make sure "couldn't" isn't simply because of environmental issues, like the network being down, etc.
Two samples:
#Example 1 $AdUser = Get-ADUser -Filter {SamAccountName -eq $SamAccountName} if ($AdUser -eq $null) {<UserDoesntExistCode>} else {<UserExistsCode>} #Example 2 $AdUser = Get-ADUser -Filter {SamAccountName -eq $SamAccountName} if ($AdUser -is 'Microsoft.ActiveDirectory.Management.ADUser') {<UserExistsCode>} else {<UserDoesntExistCode>}
Be aware that I'm assuming the match is simply on the samAccountName attribute. If you want to search more broadly (but maybe get multiple responses), you could try other attributes, or the ambiguous name resolution feature.