我有来自客户端的CSV,其中包含几列。电子邮件列,SamAccountName,SecurityGroups。
在“安全组”列中,每个安全组之间用“,”分隔 每行看起来如下
User1 User1@email.com SecurityGroup1, SecurityGroup2, SecurityGroup3
User2 User2@email.com SecurityGroup1, SecurityGroup2, SecurityGroup3
User3 User3@email.com SecurityGroup13, SecurityGroup5, SecurityGroup6
不同安全组中的用户列表,如何阅读CSV并仅添加每个用户需要的安全组。
以下是我到目前为止,当我在WhatIf模式下运行它时,它将所有安全组添加到一个用户。
Clear
$ADGroup = $null
$i = 0
$ADGroup = import-csv 'File.csv'
$sADGroup = $ADGroup.'Groups required'
Import-CSV "TestUsers.csv" | % {
$SAM = $_.SamAccountName
$ADUser = Get-Aduser -filter {SamAccountName -eq $SAM} -Properties * | Select SamAccountName, MemberOf
Write-Host 'SamAccountName :' $_.SamAccountName ' - ADUser - ' $SAM
$sADGroup | ForEach-Object{
Write-HOst $ADGroup.ADgroup[$i]
Add-ADGroupMember $sADGroup.split(",")[$i] -Members $ADUser.SamAccountName -WhatIf
$i += 1
}
}
答案 0 :(得分:0)
这是最终的脚本,使用AD-ADPrincipalGroupMembership是find,而不是使用Add-ADGroupMember
Import-Csv 'testusers.csv' |
ForEach-Object {
add-content $LogFile "Adding User to Group - $($_.Name)"
Try{
Add-ADPrincipalGroupMembership -identity $_.'SamAccountName' -memberof ($_.'Groups' -split', ')
}
Catch {
Add-content $LogFile "Error adding user to group - $($_.Name)"
}
}