在尝试"选择"之前,我有一个检查AD的功能。用户名;它首先假设第一个首字母+姓氏,看看它是否已经在AD中。
如果是,它会添加来自名字的字母,直到找到未使用的用户名。如果它耗尽了名字中的所有字母,它将在最后添加一个递增的数字(即jdoe,jodoe,johdoe,johndoe,johndoe1,johndoe2等):
注意:这假设您的名字为$FirstName
,姓氏为$LastName
尝试运行脚本时,我收到以下错误消息:
Get-ADUser:找不到具有身份的对象:' JDoe'在:>' DC = contoso,DC = com'。 在行:18 char:31 + $ usernameExists = Get-ADUser<<<< $ username -ErrorAction> SilentlyContinue |格式范围的IsValid + CategoryInfo:ObjectNotFound:(JDoe:ADUser)[Get-ADUser],> ADIdentityNotFoundException + FullyQualifiedErrorId:找不到具有标识的对象:' JDoe' >下:>' DC = contoso,DC = com'。,Microsoft.ActiveDirectory.Management.Commands.GetADUser 将用户名设置为JDoe
我假设有一个与IsValid
参数有关的问题?
$firstname_auto = $firstname.ToLower()
$lastname_auto = $lastname.ToLower()
$FirstNameLength = ($firstname_auto | Measure-Object -Character).Characters
$letterCount = 0
$username = ''
#Try to spell out the entire first name until we can get a unique username
do {
$letterCount++
$usernameExists = $false
$username = "$($firstname_auto.Substring(0,$letterCount))$($lastname_auto)"
$usernameExists = Get-ADUser $username -ErrorAction SilentlyContinue | format-wide IsValid
if ($usernameExists -eq $true) {
Write-Verbose "$username exists in AD. Trying again."
}
} until (($usernameExists -eq $false) -OR ($letterCount -eq $FirstNameLength))
#If we've used all the letters in the first name, and the username still isn't unique,
#start counting until we find one that is.
if ($usernameExists -eq $true) {
$usernameNumber = 0
Write-Verbose "Exhausted all non-numeric options! Trying with numbers."
do {
$usernameNumber++
$usernameExists = $false
$username = "$($firstname_auto.Substring(0,$letterCount))$lastname_auto$usernameNumber"
$usernameExists = Get-ADUser $username -ErrorAction SilentlyContinue | format-wide IsValid
if ($usernameExists -eq $true) {
Write-Verbose "$username already exists in AD. Trying again."
}
} until ($usernameExists -eq $false)
}
Write-host "Setting username as $username" -foregroundcolor Green