我的脚本工作正常,可以创建一个新的Active Directory用户。我需要修改脚本以将用户添加到其安全组。
以下是我的CSV文件的内容:
Firstname,Lastname,Password,Sam,Group
Alice,Gadbois,azerty+123,a.gadbois,GG1
Quincy,Lagueux,azerty+123,q.lagueux,GG1
这是我的PowerShell脚本:
$objOU = [ADSI]"LDAP://OU=TestOU,DC=Domain,DC=local";
$dataSource = import-csv -Path "c:\users.csv";
foreach($dataRecord in $datasource) {
$cn = $dataRecord.FirstName + " " + $dataRecord.LastName
$sAMAccountName = $dataRecord.Sam
$givenName = $dataRecord.FirstName
$Password = $dataRecord.Password
$sn = $dataRecord.LastName
$sAMAccountName = $sAMAccountName.ToLower()
$displayName = $sn + ", " + $givenName
$userPrincipalName = $sAMAccountName + “@domain.local"
$objUser = $objOU.Create("user","CN="+$cn)
$objUser.Put("sAMAccountName",$sAMAccountName)
$objUser.Put("userPrincipalName",$userPrincipalName)
$objUser.Put("displayName",$displayName)
$objUser.Put("givenName",$givenName)
$objUser.Put("sn",$sn)
$objUser.SetInfo()
$objUser.psbase.InvokeSet(“AccountDisabled",$false)
$objUser.SetInfo()
}
我需要在脚本中添加一个新命令,将每个用户添加到他的组中。
答案 0 :(得分:2)
使用远程服务器管理工具(RSAT)附带的ActiveDirectory
PowerShell模块。它有一个名为Add-ADGroupMember
的命令。
答案 1 :(得分:1)
你走了:
正如Trevor所说,您需要在脚本顶部导入Active Directory模块。
Import-module ActiveDirectory
然后在foreach循环中,您可以添加Add-ADGroupMember命令。
foreach($dataRecord in $datasource) {
$cn = $dataRecord.FirstName + " " + $dataRecord.LastName
$sAMAccountName = $dataRecord.Sam
$givenName = $dataRecord.FirstName
$Password = $dataRecord.Password
$sn = $dataRecord.LastName
$sAMAccountName = $sAMAccountName.ToLower()
$displayName = $sn + ", " + $givenName
$userPrincipalName = $sAMAccountName + “@domain.local"
$objUser = $objOU.Create("user","CN="+$cn)
$objUser.Put("sAMAccountName",$sAMAccountName)
$objUser.Put("userPrincipalName",$userPrincipalName)
$objUser.Put("displayName",$displayName)
$objUser.Put("givenName",$givenName)
$objUser.Put("sn",$sn)
$objUser.SetInfo()
$objUser.psbase.InvokeSet(“AccountDisabled",$false)
$objUser.SetInfo()
Add-ADGroupMember -Identity $dataRecord.Group -Member $sAMAccountName
}
故障排除
验证每个用户是否已正确分配组:
$users = Import-Csv "Path_To_File.csv"
$users | % {
$_.Group
}