[英]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.