Create New AD-User and Count if found

2019-09-10 05:52发布

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.

2条回答
在下西门庆
2楼-- · 2019-09-10 06:07

A solution that does not involve try catch statements in case there are other issues with Get-AdUser.

$accountname = "account"
$count = $null
do{
    $query = "(&(objectClass=user)(samaccountname=$accountname$count))"
    $result = ([adsisearcher]$query).FindOne()
    If($result){If($count -eq $null){$count = 2}Else{$count++}}
}While($result)

Write-Host "The account name you should use is: $accountname$count"

[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 using Get-Variable but it's needlessly complicated.)

查看更多
叛逆
3楼-- · 2019-09-10 06:11

Here's roughly how I would do this (NOTE: untested, since my AD doesn't use this naming scheme):

$samAccountName = 'smithjw'
$count = 2
if (Get-ADUSer $samAccountName -ErrorAction Silently Continue) {
    while (Get-ADUser "$samAccountName$Count" -ErrorAction SilentlyContinue) {
        $count++
    }
    #create "$samAccountName$count"
}
else {
    #just create smithjw
}
查看更多
登录 后发表回答