![使用 PowerShell 从 CSV 生成 aAMAccountName(子字符串)](https://linux22.com/image/765198/%E4%BD%BF%E7%94%A8%20PowerShell%20%E4%BB%8E%20CSV%20%E7%94%9F%E6%88%90%20aAMAccountName%EF%BC%88%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%89.png)
我有一个问题,您可能希望帮助我解答疑问,我写了一个从 Excel 文件导入所有用户的脚本。
问题是我如何生成以特定字符串开头的 sAMAccountName,例如,用户名是 Joris Ahamd。我希望 Joris sAMAccountName 应该像 GOTJAH 那样,Joris 名字的首字母 J 和姓氏的前两个字母 AH 和“GOT”作为所有用户的默认设置。
我希望这足够清楚,否则我会尝试进一步解释。
以下是脚本
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\Script\Poweshell\samer1.csv
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou #This field refers to the OU the user account is to be created in
$email = $User.email
$streetaddress = $User.streetaddress
$city = $User.city
$zipcode = $User.zipcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$Password = $User.Password
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $username `
-UserPrincipalName "[email protected]" `
-Name "$Lastname,$Firstname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path "OU=Malmo,DC=consilium,DC=net"`
-City $city `
-Company $company `
-State $state `
-StreetAddress $streetaddress `
-OfficePhone $telephone `
-EmailAddress $email `
-Title $jobtitle `
-Department $department `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
答案1
你没有说你正在使用哪个 shell,但是假设是 bash:
PREPEND='GOT'
SamAccountName="$PREPEND${Firstname:0:1}${Lastname:0:2}"
答案2
由于您的脚本是用 PowerShell 编写的,因此我假设您希望使用该语言的解决方案。您应该使用Substring() 方法提取您需要的名称部分。
以下是一些可帮助您入门的示例代码:
PS C:\> $Firstname = "Joris"
PS C:\> $Lastname = "Ahamd"
PS C:\> $Firstname.Substring(0,1)
J
PS C:\> $Lastname.Substring(0,2)
Ah
PS C:\> $Username = ("GOT"+$($Firstname.Substring(0,1))+$($Lastname.Substring(0,2))).ToUpper()
PS C:\> $Username
GOTJAH