【发布时间】:2021-09-15 20:51:50
【问题描述】:
PowerShell 初学者在这里....
我需要清理 AD 中包含数千个帐户的已终止用户 OU。我想从每个帐户中删除所有组,除了 2 个特定组(域用户和一个许可组)。
谁能指出我正确的方向来了解这个脚本的外观?我在网上找到了一些示例,但似乎找不到任何解释如何排除组的内容。
我发现了一些可以让我从单个组中删除人员列表的东西.....但我不确定如何将其转换为删除所有组的东西,除了我想要排除的组。
Start-Transcript -Path -Append
# Import the data from CSV file and assign it to variable
$Users = Import-Csv ""
# Specify target group where the users will be removed from
# You can add the distinguishedName of the group. For example: CN=Pilot,OU=Groups,OU=Company,DC=exoip,DC=local
$Group = groupname
foreach ($User in $Users) {
# Retrieve UPN
$UPN = $User.UserPrincipalName
# Retrieve UPN related SamAccountName
$ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'" | Select-Object SamAccountName
# User from CSV not in AD
if ($ADUser -eq $null) {
Write-Host "$UPN does not exist in AD" -ForegroundColor Red
}
else {
# Retrieve AD user group membership
$ExistingGroups = Get-ADPrincipalGroupMembership $ADUser.SamAccountName | Select-Object Name
# User member of group
if ($ExistingGroups.Name -eq $Group) {
# Remove user from group
Remove-ADGroupMember -Identity $Group -Members $ADUser.SamAccountName -Confirm:$false -WhatIf
Write-Host "Removed $UPN from $Group" -ForeGroundColor Green
}
else {
# User not member of group
Write-Host "$UPN does not exist in $Group" -ForeGroundColor Yellow
}
}
}
Stop-Transcript
【问题讨论】:
-
我们可以看看你在这方面的尝试吗?
-
那么,如果您将用户从他们所属的所有组中剥离出来,为什么还要指定一个组呢?如果每个用户的
MemberOf列表中存在某些组(在 Get-ADUser 上使用参数-Properties指定),排除它们应该不会太难。附言添加| Select-Object SamAccountName和| Select-Object Name是不必要的,if ($ADUser)比if ($ADUser -eq $null)更好
标签: powershell active-directory