将新创建的用户添加到预先存在的组
此脚本当前在从 CSV 文件导入数据后创建新用户
This script currently creates new users after importing data from a CSV file
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "@NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
}
这是我从中导入的 csv 文件:
This is the csv file I am importing from:
Name,samAccountName,ParentOU,Group
Test Test1,TTest1,"OU=Business,DC=NWTC,DC=local",TestGroup
创建用户后,我想将其添加到已存在的组中.我希望将不同的用户添加到不同的组中,但每人只能添加 1 个组.
After a user is created, I want to add them to an already exisiting group. There will be different groups I want different users to be added to, but only 1 group per person.
我一直在尝试使用 Add-AdGroupMember
,但我不确定如何继续.像这样:Add-ADGroupMember -Members $_.Members
.这是我第一次使用 CSV,所以我进入了新领域
I've been playing around with Add-AdGroupMember
, but I'm not sure how to proceed. Something like this: Add-ADGroupMember -Members $_.Members
. This is the first time I'm working with CSVs, so I'm in new territory
New-ADuser
不支持此功能,因此您必须事后自己做.您可以做的是让 New-ADUser
吐出它创建的 AD 用户对象,并将其与 Add-ADGroupMember
一起使用.
New-ADuser
does not support this functionality so you will have to do that yourself after the fact. What you could do is have New-ADUser
spit out the AD user object it creates and use that with Add-ADGroupMember
.
$newUserProperties = @{
Name = $_.Name
Path = $_."ParentOU"
SamAccountName = $_."samAccountName"
UserPrincipalName = $_."samAccountName" + "@NWTC.local"
AccountPassword = (ConvertTo-SecureString "Password1" -AsPlainText -Force)
ChangePasswordAtLogon = $false
Enabled = $true
}
try{
$newADUser = New-ADUser @newUserProperties -PassThru
Add-ADGroupMember -Identity $_.Group -Members $newADUser.SamAccountName
} catch {
Write-Warning "Could not create $($newUserProperties.samaccountname)"
}
错误处理很粗糙,但应该以某种形式存在,以解决源数据中的故障或现有用户的误解.基本上只是获取 $newADUser
并将其用于 Add-ADGroupMember
The error handling is crude but should exist in some form to account for failures in the source data or misconceptions of existing users. Basically just getting $newADUser
and using it for Add-ADGroupMember
我们在这里使用参数的散列.这样您就不必担心通过使用反引号来获得格式良好的代码.
We use splatting of the parameters here. That way you don't have to worry about having nice formatted code by using backticks.