简体   繁体   中英

Using Powershell to remove a user from a list of groups

Trying to get this script to remove a user from a list of groups.

Not sure what part of my language here is wrong. It doesn't return an error in ISE. I'm admittedly a rookie in writing my own powershell scripts instead of modifying others. Any help is appreciated.

Import-Module ActiveDirectory
$group = @('grouopname1','groupname2','groupname3')
$user = "testa"

if ($user.Memberof -like $group)
{
    foreach ($user in $group )
    {
     Remove-ADPrincipalGroupMembership -identity $user -MemberOf $group -confirm:$False
    }
}

On thing you'll need to learn when using PowerShell is that it's very important to test what kind of output and object will give you.

$user = "testa" | $user.MemberOf

That will give you an error, because a string doesn't have a member property "MemberOf"

$user = Get-ADUser testa -Properties MemberOf

That will give you an object containing the user "testa", and since the MemberOf property isn't retrieved by default, you will need to add it in.

$user.MemberOf

This will return the DistinguishedName of all groups that the user is a member of, but it will not get nested groups... that would require more logic, but you can find that if you search for it.

Your group array would work... if you do a replace on $user.MemberOf so that it only returns the Common Name, but you can easily just compare the DNs. To do that however, you would need to do something like this:

$groups = $group | foreach ($g in $group) { Get-ADGroup $g }

Not pretty, but it will get you there.

The final part of the loop can be something like this:

foreach ($u in ($user.MemberOf))
{
    if (($groups.DistinguishedName) -Contains $u)
    {
        Do-Whatever
    }
}

I would generally start with a test inside the loop, using Write-Host or -WhatIf to verify just what was going to be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM