Powershell - Get-ADOrganizationalUnit Groups

57,744

Solution 1

From Get-ADOrganizationalUnit

Here is how you're supposed to use -Identity (from the examples at the bottom of the above document):

Get-ADOrganizationalUnit -Identity 'OU=AsiaPacific,OU=Sales,OU=UserAccounts,DC=FABRIKAM,DC=COM'

So I suspect your 'ou=OUName' needs the relevant DC=domain,DC=com information on the end.

To remove users I'd go about doing it this way:

Get-ADGroup -SearchBase "OU=AsiaPacific,OU=Sales,OU=UserAccounts,DC=FABRIKAM,DC=COM" -filter {GroupCategory -eq "Security"} | Get-ADGroupMember | Remove-ADGroupMember -WhatIf

Replace -WhatIf with -Confirm:$false if you're happy this does what you need.

Solution 2

If you want to retrieve all the groups in a particular OU. I'd use:

get-adobject -Filter 'ObjectClass -eq "group"' -SearchBase <<Path to OU>>

Passing the returned objects to Get-ADGroupMember will give you the current membership. Then use remove-adgroupmember to strip out the existing members and add-adgroupmemeber to add the names from the txt file.

Share:
57,744
Richard
Author by

Richard

Updated on November 09, 2020

Comments

  • Richard
    Richard over 3 years

    I'm starting to get my head around powershell. But then again maybe not! Can someone please tell me how to list all security groups within a OU?

    I am able to list all the members within a group, for example:

    get-adgroupmember "groupName" | select-object name
    

    In the following, I am trying to list all security groups within an OU:

    Import-Module ActiveDirectory
    Get-ADOrganizationalUnit -Identity 'ou=OUName'
    
    ERROR: Cannot find object with identity: ......
    

    I would like to remove all members from all security groups in a particular OU. Then I would like to add group members from a text file.

  • Robin
    Robin over 10 years
    Would this potentially return distribution groups as well? The filter would need expanding to target GroupCategory also I think!
  • Arcass
    Arcass over 10 years
    Hi Rob, you are correct this will return anything of Ojbect Class group. You would need to further filter on the GroupType propoerty to get just security groups. As per this post: blogs.technet.com/b/heyscriptingguy/archive/2004/12/21/…