以下腳本將帳戶添加到 Active Directory。如果用戶名已經存在,我想在用戶名上附加一個數字并重試。
即如果cs15csa
已經存在,它應該再試一次cs1csa2
。如果cs1csa2
存在,則應嘗試使用cs1csa3
,依此類推。
我怎么做?
# Enter a path to your import CSV file
$ADUsers = Import-csv export.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
# Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
# If user does exist, output a warning message
Write-Warning "A user account $Username ($Firstname $Lastname) already exists in the Active Directory."
}
else
{
# If a user does not exist then create a new user account
# Account will be created in the OU listed in the $OU variable in the CSV file; don't forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username@iit.uni-ruse.bg" `
-Email "$Username@iit.uni-ruse.bg" `
-ProfilePath '\\leo\%USERNAME%\Profile' `
-Name "$Username" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
uj5u.com熱心網友回復:
您可以簡單地使用一個回圈來測驗 SamAccountName 并在里面不斷添加一個計數器編號,直到您找到一個唯一的名稱。
為了避免在 New-ADUser cmdlet 上使用那些討厭的反引號,我建議使用Splatting
還有,'\\leo\%USERNAME%\Profile'
應該"\\leo\$Username\Profile"
嘗試
# Enter a path to your import CSV file
$ADUsers = Import-Csv export.csv
foreach ($User in $ADUsers) {
$Username = $User.username
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
$count = 2
while (Get-ADUser -Filter "SamAccountName -eq '$Username'") {
$Username = '{0}{1}' -f $User.username, $count
}
# create the new user using a Splatting Hashtable
$userParams = @{
SamAccountName = $Username
UserPrincipalName = "[email protected]"
EmailAddress = "[email protected]"
ProfilePath = "\\leo\$Username\Profile"
Name = $Username
GivenName = $User.firstname
Surname = $User.lastname
Enabled = $true
DisplayName = '{0} {1}' -f $User.firstname, $User.lastname
Path = $User.ou
AccountPassword = $User.password | ConvertTo-SecureString -AsPlainText -Force
}
# create the user
New-ADUser @userParams
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/527288.html
標籤:电源外壳