Remove-ADPrincipalGroupMembership脚本不会删除用户

时间:2015-04-02 14:14:09

标签: powershell-v2.0

我有以下脚本运行没有错误,但它不会从组中删除用户。我不确定我错过了什么。我已经尝试在没有用户名变量和实际名称的情况下运行它,但这也不起作用。在此先感谢您的帮助。

$group = @(
'Aberdeen Refer Team','Air Force Refer Team','Coliseum Refer Team','Denbigh Refer Team','Warwick Refer Team','Wards Corner Refer Team',
'Eagle HarborRefer Team','Chesapeake Refer Team','Willow Oaks Refer Team','poquoson Refer Team','Oyster Point Refer Team','NASA ReferTeam',
"Contact Center Refer Team",'Yorktown Refer Team','WB New Town Refer Team','WB City Refer Team','Stoneybrook Refer Team',
'Hayes Refer Team','Hilltop Refer Team')

$user = Get-aduser "%username%" -Properties MemberOf
if ($user.MemberOf -match $group)
{
    foreach ($group in $user)
    {
Remove-ADPrincipalGroupMembership -identity $user -MemberOf $group -confirm:$False
}
}

1 个答案:

答案 0 :(得分:0)

%username%替换为$env:USERNAME以获取用户名,然后使用Get-ADPrincipalGroupMembership找到所有用户的群组:

$TeamNames = @('Aberdeen Refer Team','Hilltop Refer Team')

$User = Get-ADUser "$($env:USERNAME)"

# Find all the groups that the user is a member of, and filter down to just those in the $TeamNames list
$UserGroups = Get-ADPrincipalGroupMembership -Identity $user | Where-Object { $TeamNames -contains $_.Name }

# Iterate over the groups
foreach ($Group in $UserGroups)
{
    # Remove each group membership from the user
    Remove-ADPrincipalGroupMembership -Identity $User -MemberOf $Group -Confirm:$false
}