【发布时间】:2018-09-03 03:30:24
【问题描述】:
我有一个创建活动目录用户的脚本,它运行良好。
在这里,我需要这些用户在创建后将他们自己添加到
一些团体。
所以我发现这是一个 cmdle Add-ADPrincipalGroupMembership
但我不知道如何将此 CmdLet 组合到我的脚本中(我在 PowerShell 上的使用时间更长)
我尝试使用另一个 foreach 语句,但没有成功
代码如下:
cls
#get the csv file
$filepath = import-csv "C:\users.csv"
#set the variable for the uers
$newusers = $filepath
#set Passwords for new users
$securepassword = ConvertTo-SecureString "blahblah" -AsPlainText -Force
#start the loop
foreach ($user in $newusers) {
#get user information
$firstname = $user.'First Name'.Trim()
$lastname = $user.'Last Name'.Trim()
$loginname= $user.SamAccountName
$UsrPrincipalName = $user.UserPrincipalName
$jobtitle = $user.'Job Title'
$Department= $user.Department
$Description = $user.Description
$OuPath= $user.Path
$LoginScript=$user.ScriptPath
$displayname= $user.DisplayName
#create the users in active directory
$vars = @{
Name = "$firstname $lastname"
GivenName = $firstname
Surname = $lastname
UserPrincipalName = $UsrPrincipalName
SamAccountName = $loginname
Path = $OuPath
ScriptPath = $LoginScript
AccountPassword = $securepassword
ChangePasswordAtLogon = $false
Department = $Department
DisplayName = $displayname
Description = $Description
Title = $jobtitle
Enabled = $true
}
#Editors comment: Make a hashtable and use splatting when specifying lots of parameters
$newcreatedusers = New-ADUser @vars -PassThru
#starting a loop for adding the users to the groups
Write-Host "`n"
Write-Host "The account for $firstname $lastname created in $OuPath successfully"
}
$filepath = $Adgroups
foreach ($group in $Adgroups){
$adgroup = $group.Groups.splite(',')
Add-ADPrincipalGroupMembership -Identity $group.Groups -members $SamAccountName
}
【问题讨论】:
-
组名从何而来?一个文本文件? CSV 文件?
-
我在 CSV 文件中添加了一列,在每一行中,以逗号分隔的标题“组”小时、记事本、终端服务器用户、纽约分公司
-
同一个 CSV 文件 $path
-
仍不清楚。您的脚本中的
$Adgroups是什么?它从未定义过。您已在用户循环之外添加了组循环,这意味着$SamAccountName不存在(这两种方式都不存在,因为您在循环内将其称为$loginname)。为组添加 csv 示例,并确保问题中的代码完整.. -
我添加了 csv 文件示例,
$adgroups是 csv 文件中组标题的变量
标签: powershell active-directory powershell-2.0