Check if account exists and if true increment a number on the end until false

Creating a user account via PowerShell? Are there many Joe Bloggs in your organisation? Want to check if BloggsJ already exists before creating the account? Well the below script will help. It runs through and checks if the user exists. if true, it will add a 1 on the end of the name and keep adding 1 until it doesn’t exist.

 



$Name = $sn5 += $givenname1
$defaultname = $name


$Exit = 0
$Count = 1

Do
{
Try

{


# Attempt to retrieve information on the user.
$User = Get-ADUser -Identity $Name

# The user exists.
$Name = $name
$Name = $defaultname + $Count++


If ($Count -gt 20) {$Exit = 1}
}
Catch
{
# User does not exist.
$Exit = 1
}
}
While ($Exit -eq 0)
$Name

0 thoughts on “Check if account exists and if true increment a number on the end until false”

  • Hi Jency,

    Thanks for the comment, Its a great point you could do it that way. I originally wanted a catch on there as didn't want it going past 20 as would indicate a problem for us. It's why PowerShell is so good, if I was to do it again it would probably look completely different :).

Leave a Reply

Your email address will not be published. Required fields are marked *