不知道你能不能给我提供帮助。我正在为同事创建一个脚本,通过Powershell向AD添加一个全新的用户。但是,我开始在脚本结束时遇到一些错误。
# Adding the AD PS Module
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
# set default password
$defpassword = (ConvertTo-SecureString "Welcome123" -AsPlainText -force)
# Get Domain DNS suffix
$dnsroot = '@' + (Get-ADDomain).dnsroot
echo "This tool is to be used for creating User Accounts for the RBFT Domain under Ultima Business Solutions only. If this applies, please hit any key to continue."
$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL
$HOST.UI.RawUI.Flushinputbuffer()
Write-Host " "
Write-Host " "
# Acquiring unique field data
$GivenName = Read-Host -Prompt "What Is The New User's First Name?"
Write-Host " "
$Initial = Read-Host -Prompt "What Is The New User's First Initial?"
Write-Host " "
$Surname = Read-Host -Prompt "What Is The New User's Last Name?"
Write-Host " "
$DisplayName = $Surname + " " + $GivenName
$Mail = $GivenName + "." + $Surname + "@" + "BLOCKEDEMAIL"
$MailAlias = $GivenName + "." + $Surname + "@" + $DNSRoot2
$Manager = Read-Host -Prompt "Who Is The New User's Manager?"
Write-Host " "
$SAMAccountName = $Surname.Substring(0,7)+$Initial.Substring(0,1)
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $Mail
start-sleep -s 5
# Create The User
Get-ChildItem
New-ADUser -path "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk" -SamAccountName $SamAccountLower -Name $DisplayName -DisplayName $DisplayName -GivenName $GivenName -Surname $Surname -EmailAddress $Mail -UserPrincipalName $Mail -Title $title -Enabled $true -ChangePasswordAtLogon $true -PasswordNeverExpires $false -AccountPassword $defpassword -PassThru
但是,这会产生以下错误
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At C:\Users\timmsj\Desktop\AD_User.ps1:42 char:1
+ $SAMAccountName = $Surname.Substring(0,7)+$Initial.Substring(0,1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
You cannot call a method on a null-valued expression.
At C:\Users\timmsj\Desktop\AD_User.ps1:43 char:1
+ $SAMAccountLower = $SAMAccountName.ToLower()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
有人能提供协助吗?
答案 0 :(得分:1)
您需要检查$Surname
的长度是否小于7,并且$Initial
是否包含至少一个字符:
if ($Surname.length -lt 7) {
$SAMAccountName = $Surname
} else {
$SAMAccountName = $Surname.Substring(0,7)
}
if ($Initial.length -ge 1){
$SAMAccountName = SAMAccountName+$Initial.Substring(0,1)
}
但要注意:您还必须检查是否尚未在域中设置生成的samAccountName!