I am attempting to implment a script to help automate account creation. It will query AD for a user and if found, add a number to the end, and then do another query. Again, if found, change the number from say 2 - 3.
Such as if the following users are already in AD:
- Smith, James W = SmithJW
- Smith, Jason W = SmithJW2
I want to add a new user, Smith, Jacob W. It should query AD for SmithJW at first, then if found, add a 2, and if found, add a 3. What I got two work below, essentially does it, but due to it finding a SmithJW2, it just adds the counter to that name. So I would get back SmithJW22.
Code:
$user = "smithjw"
Do{
$adcheck = $null
$counter = 2
Try {$adcheck = Get-Aduser $user
}
Catch {If($adcheck.SamAccountName-eq$null){$NewUserName = $user}
}
If($adcheck.SamAccountName-ne$null){$user = $user+$counter++}
}until($adcheck.SamAccountName-eq$null)
So I'm looking for a way to if I find a user (i.e. SmithJW2) to remove the "2" first, then add the counter.
Hopefully this makes sense. Thanks.
A solution that does not involve try catch statements in case there are other issues with
Get-AdUser
.[adsisearcher]$query).FindOne()
would return$null
if there is not object found. So loop until$result
is empty/null. I'm not happy with how the$count
is handled but it does work. The$count
is changed if there is a returned user. If there is the$count
needs to be changed. Since you start 2 we need to check if its the first time the variable is going to be set. There are other ways but this is consistent and readable. (I have an idea usingGet-Variable
but it's needlessly complicated.)Here's roughly how I would do this (NOTE: untested, since my AD doesn't use this naming scheme):