powershell - 尝试创建一个powershell用户创建脚本,如果它已经存在,想要将数字附加到用户名
问题描述
我正在尝试创建一个用户创建脚本,以此来自学更多 Powershell。目前我只致力于创建用户名,并希望确保每个用户名都是唯一的。
在用户输入用户的姓名和号码后,脚本应该执行以下操作。
获取名字 获取中间首字母 获取姓氏 组合名字的第一个字母 + 中间名首字母 + 姓氏的 6 个字符 如果用户已经存在,则从 1 开始添加数字,直到用户名唯一。我目前停留在第 5 步。如果用户名不是唯一的,它会附加一个数字。IE 用户 Brenda T Follower 的用户名是 BTFollow,如果该用户名已经存在,它将变为 BTFollow1。
但是,如果 BTFollow 和 BTFollow1 已经存在,而不是生成 BTFollow2,它会生成 BTFollow12。
最后,虽然不是一个大问题,但我希望我的参数显示 Read-Host 之后的内容,但该文本不仅仅出现在变量名中。
这是我的代码。
Param(
#Gather users first name, required input and must not be empty or null
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string]
$FirstName = (Read-Host -Prompt 'Please input the users first name.'),
#Gather users middle initial, required input and must not be empty or null and must only be one character
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[ValidateLength(1,1)]
[string]
$MiddleInitial = (Read-Host -Prompt 'Please input the users middle initial.'),
#Gather users last name, required input and must not be empty or null
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string]
$LastName = (Read-Host -Prompt 'Please input the users last name.'),
#Gathers user phone extension, required input, mustn ot be empty or null, and must only user numbers
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[ValidatePattern("[0-9][0-9][0-9][0-9]")]
[ValidateLength(4,4)]
[String]
$PhoneExtension = (Read-Host -Prompt 'Please input the users 4 digit exension, numbers only')
)
$i = 0
#Create user name
$Username = $FirstName.Substring(0,1) + $MiddleInitial + $LastName.Substring(0,6)
#Check username does not exist, if it does add numbers
Do {
Try {
Get-ADUser $UserName | Out-Null
$UserName = $Username + ++$i
Continue
}
Catch {
Break
}
} While ($True)
Write-Host "Username is $Username"
解决方案
在 Reddit 的帮助下想通了。我需要替换我当前的代码。
Do {
Try {
Get-ADUser $UserName | Out-Null
$UserName = $Username + ++$i
Continue
}
Catch {
Break
}
} While ($True)
有效的新代码。
#Check username does not exist, if it does add numbers
$UniqueUserName = $Username
while (Get-ADUser -Filter "SamAccountName -like '$UniqueUserName'"){
$UniqueUserName = $Username + ++$i
}