[英]Powershell Active Directory username
對於一個學校項目,我需要制作一個 Powershell 腳本,但是要創建一個用戶名,只有人名的第一個字母和完整的第二個名字,有人可以幫我嗎? 這是我目前擁有的:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
ForEach ($user in $users) {
# Gather the user Information
$fname = $user.FirstName
$lname = $user.LastName
$jtitle = $user.JobTitle
$OUpath = $user.OU
Write-Host $fname
Write-Host $lname
Write-Host $jtitle
Write-Host $OUpath
#Gebruiker aanmaken in AD
New-ADUser -Name "$fname $lname" -GivenName $fname -SamAccountName $lname -Surname $lname -UserPrincipalName "$lname" -Path $OUpath -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true
}
根據其他人的評論。 在$lname =...
之后添加這一行
$sam = "{0}$lname" -f $fname.Substring(0,1)
然后使用$sam
編輯您的New-ADUser
行
New-ADUser .... -SamAccountName $sam ...
將我的評論變成答案。
您可以很容易地創建用戶的 SamAccountName,將用戶 GivenName 的第一個字符與完整的 LastName 結合起來。 但是,您需要檢查此 SamAccountName 是否尚未在使用中。
另一件事是UserPrincipalName
應該采用<user>@<DNS-domain-name>
的形式。
要改進您的代碼,還可以使用 Splatting:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
foreach ($user in $users) {
# first create the desired SamAccountName for the new user
$accountName = "{0}{1}" -f $user.FirstName.Substring(0,1),$user.LastName
# test if a user with that SamAccountName already exists
$checkUser = Get-ADUser -Filter "SamAccountName -eq '$accountName'" -ErrorAction SilentlyContinue
if ($checkUser) {
Write-Warning "SamAccountName $accountName already used for user $($checkUser.Name)"
}
else {
# create a hashtable with all parameters for the New-ADUser cmdlet
$userParams = @{
Name = "$fname $lname"
GivenName = $user.FirstName
Surname = $user.LastName
Title = $user.JobTitle
SamAccountName = $accountName
Path = $user.OU
AccountPassword = $securePassword
PasswordNeverExpires = $true
Enabled = $true
UserPrincipalName = "$accountName@yourdomain.com" # <-- put YOUR domain here after the '@'
# other parameters go here if needed
}
New-ADUser @userParams
}
}
另外,請記住,您不能只對 SamAccountName 使用任何字符。 字符" [ ]: ; | = + *? < > / \, @
是非法的,以及不可打印的字符和點.
不能是名稱的最后一個字符。
並且,系統將用戶對象的 sAMAccountName 限制為 20 個字符。
為了確保,使用類似的東西:
$accountName = ($accountName -replace '["\[\]:; |=+\*\?<>/\\,@]').TrimEnd(".") -replace '^(.{1,20}).*', '$1'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.