D
D
Dmitry Shumov2021-03-26 16:17:07
PowerShell
Dmitry Shumov, 2021-03-26 16:17:07

I can't understand why the script fails with an error?

Colleagues, there is a script that removes all groups from blocked users, except for "Domain Users":

$Token = (Get-ADGroup "Domain Users" -Properties PrimaryGroupToken).PrimaryGroupToken

Get-ADUser -Filter 'Enabled -eq "False"' -SearchBase "DC=domen,DC=local" -Properties PrimaryGroup,MemberOf | ForEach-Object {

#If User Primary Group is not Domain Users, then Set Domain User as Primary Group.
If ($_.PrimaryGroup -notmatch "Domain Users"){ 
             Set-aduser -Identity $_ -Replace @{PrimaryGroupID = $Token } -Verbose
                                               } #If

#If User is a member of more than 1 Group. Remove All Group except Domain Users.
If ($_.memberof) {
            $Group = Get-ADPrincipalGroupMembership -Identity $_ | Where-Object {$_.Name -ne 'Domain Users'}
                     Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $Group -Confirm:$false -Verbose
                  } #If

}

On a small number of users, it works well. But it’s worth setting it on the entire domain, after working a little, it falls out with an error:
Get-ADUser : The server has returned the following error: invalid enumeration context.
At C:\Scripts\Очистка AD\remove Disabled Users from All AD Groups.ps1:3 char:1
+ Get-ADUser -Filter 'Enabled -eq "False"' -SearchBase "OU=Filials,DC=nasta,DC=loc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADUser

I can't figure out why.... :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
azarij, 2021-03-26
@dshumov

there is an opinion that if you put the output of the first command into a variable and dance further from the variable, then it will work:

$users = Get-ADUser -Filter 'Enabled -eq "False"' -SearchBase "DC=domen,DC=local" -Properties PrimaryGroup,MemberOf

$users | ForEach-Object {

#If User Primary Group is not Domain Users, then Set Domain User as Primary Group.
If ($_.PrimaryGroup -notmatch "Domain Users"){ 
             Set-aduser -Identity $_ -Replace @{PrimaryGroupID = $Token } -Verbose
                                               } #If

#If User is a member of more than 1 Group. Remove All Group except Domain Users.
If ($_.memberof) {
            $Group = Get-ADPrincipalGroupMembership -Identity $_ | Where-Object {$_.Name -ne 'Domain Users'}
                     Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $Group -Confirm:$false -Verbose
                  } #If

}

or you need to change some option in the AD web service, which Microsoft does not recommend doing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question