我正在尝试为AD清理工作创建一个CSV,其中包含几百个用户SamAccountName
以及要从中删除用户的组列表。每个用户都有一个不同的组列表,可以将其从中删除。
CSV将如下所示:
SamAccountName,ADgroupName1,ADgroupName2,ADgroupName3,ADgroupName4,etc... user1,Group1,Group2,Group3,Group4 user2,Group2,Group3,,, user3,Group5,,,,
我到目前为止的脚本:
# Get the list of SAMAccountNames
$user = Import-Csv .\GroupsToRemove.csv | Select-Object -ExpandProperty SAMAccountName
foreach ($user in $users) {
# Loop through the user list and select the list of groups to remove for each user
# from the CSV and set to the $Groups array
$Group = @()
$Group = %{(Import-Csv .\GroupsToRemove.csv | Where-Object {$_.SamAccountName -eq $user})} | select "GroupName*"
foreach ($group in $Groups) {
# Remove the AD groups from each User
Remove-ADPrincipalGroupMembership $user -Member $Group -Confirm:$false
}
}
我认为部分问题是,当我从CSV导入组名时,它还会将列名添加到$Group
数组中?那么Remove-ADPrincipalGroupMembership
命令失败了吗?
$groups
输出如下:
GroupName1 : Group1 GroupName2 : Group2 GroupName3 : Group3 GroupName4 : Group4
答案 0 :(得分:1)
不要将AD组定义为CSV中的单独列。使用逗号(或其他分隔符)分隔的字符串使组成为一列:
SamAccountName,Groups user1,"Group1,Group2,Group3,Group4" user2,"Group2,Group3" user3,"Group5"
这样你可以像这样处理CSV中的组:
$csv = Import-Csv .\GroupsToRemove.csv
foreach ($user in $csv) {
$groups = $user.Groups -split ',' |
Get-ADGroup |
Select-Object -Expand DistinguishedName
Remove-ADPrincipalGroupMembership $user.SamAccountName -Member $groups -Confirm:$false
}