从以“Group-”开头的所有组中删除已禁用的帐户

时间:2015-01-27 15:08:33

标签: powershell-v3.0

我正在尝试从以Group-开头的所有群组中删除所有已禁用的帐户。我们有几个以Groups-开头的通讯组,例如Groups-users-internalgroups-users-external等等。 我有一个脚本,但我收到了消息:

Remove-ADGroup : A positional parameter cannot be found that accepts argument '(name=Groups-sites-*)'.
At line:1 char:139
+ Get-ADGroup -LDAPFilter “(name=Groups-sites-*)” | Get-ADGroupMember | Get-ADUser ...

到目前为止我的脚本如下 请帮忙

Get-ADGroup -LDAPFilter “(name=Groups-sites-*)” | Get-ADGroupMember | Get-ADUser | Where-Object {$_.Enabled -eq $False} | 
ForEach-Object {Remove-ADGroup -Identity -LDAPFilter “(name=Groups-sites-*)” -Members $ -Confirm:$False}

1 个答案:

答案 0 :(得分:1)

我会根据我对PoSh第3版的经验回复:

首先,代码中存在轻微的语法错误。在char 139,您有{Remove-ADGroup ..正确的语法是' Remove-ADGroupMember'。

Remove-ADGroupMember没有-ldapfilter开关。在这种情况下,您需要将代码分成几行,因为您需要获得' get'每个对象和'进程'每个对象连续或一次一个项目。

# Using -whatif switch.  ** Remove whatif switch only when happy with desired result.
# Assumptions - all group members are users. Use Try{}Catch{} to handle errors.
# 

# Collect all groups into array
$groups = (Get-ADGroup -LDAPFilter "(name=Group-*)").name

# Process each group one at a time
ForEach($group in $groups){

    # Get all members
    $members=Get-ADGroupMember -Identity $group;

    # Process disabled accounts for removal
    $members | ForEach{
        If($_.enabled -eq $false){

            #Output member to be removed to screen
            $_ | Select Name,SAMAccountName,Enabled;

            #Remove disabled member from group
            Remove-ADGroupMember -identity $group -Members $_.samaccountname -confirm:$false -whatif

        } 

    } # Next Member

} # Next Group