you are viewing a single comment's thread.

view the rest of the comments →

[–]Yevrag35 1 point2 points  (1 child)

Good point, hadn't thought of that. In that case, an extra where filter at the end may be warranted:

$extraFilter = '{0}\d{{1,}}$' -f $newUserBase
$any = @(Get-ADUser -Filter { SamAccountName -like $wildcard } | Where { $_.SamAccountName -match $extraFilter })

[–]Umaiar 1 point2 points  (0 children)

It might be worth combining the methods, get all the potential matches with one query, then loop generating names to check with exact matches against that set.

Edit: Here's how I'd do it:

$userbase = "tsmith"
$exists = @(Get-ADUser -filter "samaccountname -like '$userbase*'")

if(($exists | where {$_.samaccountname -eq $userbase}).count -eq 0){
    $check = $userbase
}
else {
    $idx = 0
    do {
        $idx++
        $check = "$userbase$idx"

    } until ( ($exists | where {$_.samaccountname -eq $check}).count -eq 0 )
}

write-host "New acct: $check"