我正在自动将新的用户帐户流程从Cherwell迁移到AD,我陷入了重复的samaccountname的困境。如果samaccountname不存在,我已经成功获得了要创建的帐户。我检查一下,现在只写输出以说是否找到了该名称。
小叮当是我的测试用户,因为她是我女儿最喜欢的角色。
$FirstName = “tinker”
$SurName = “bell”
for ($i = 1; $i -le $SurName.Length; ++$i) {
$Account = $null;
$Identity = $FirstName + $SurName.Substring(0,$i)
$Account = Get-ADUser -Filter {sAMAccountName -eq $Identity}
if ($Account -eq $null) {"User does not exist in AD"}
Else {"User found in AD"}
write-Output $Identity
}
我已经准备好要执行的操作,只是不确定在创建下一个samaccountname时如何停止它。
这就是我得到的输出
User found in AD
tinkerb
User does not exist in AD
tinkerbe
User does not exist in AD
tinkerbel
User does not exist in AD
tinkerbell
因此,它正确地执行了第一部分,找到了帐户,然后转到下一个帐户,但是随后它循环了,我不确定如何丢弃它,以便在此示例中创建名为$ newSam的变量确定为“ tinkerbe”。
S。
答案 0 :(得分:1)
将您的代码转换成一个简单的函数,该函数返回第一个可用的用户名:
function New-Username
{
param(
[string]$FirstName,
[string]$SurName
)
for ($i = 1; $i -le $SurName.Length; ++$i) {
$Account = $null;
$Identity = $FirstName + $SurName.Substring(0,$i)
$Account = Get-ADUser -Filter {sAMAccountName -eq $Identity}
if ($Account -eq $null) {
return $Identity
}
else {
Write-Warning "User found in AD: $Identity"
}
}
throw "Unable to generate distinct username"
}
及其用法:
$NewUsername = New-Username -FirstName tinker -SurName bell
New-ADUser -SAMAccountName $NewUserName