powershellactive-directorygroup-membership

PowerShell Check User Group Membership


I am writing a powershell script to to change GPO Ownership and I am able to change the Ownership of the GPO's to a new user. What I am wanting to do is verify that the current owner of the GPO is no long an employee. This is for a school situation and there are Students and Employees. Students belong to "Student Domain Users" while Employees belong to just "Domain Users". I am able to pull all the groups a member belongs to, however, I want to use [bool] to just set true or false.

This is what I am working with

Get-ADPrincipalGroupMembership -Identity 12345 | select SamAccountName

SamAccountName
--------------
Domain Users
Organization Management
Enterprise Admins
Domain Admins
Schema Admins

In the above example I can see that the Domain Admins is listed. I am trying to only pull that out with this code and I don't even know if it is possible. Here is what I have tried and none have worked

Get-ADPrincipalGroupMembership -Identity 12345 | select SamAccountName | select Domain Admins

Get-ADPrincipalGroupMembership -Identity 12345 | where {SamAccountName -like "Domain Admin"}

Thanks in advance for the help.

This is kind of what I am wanting to do with it as a verification process - this verifies that the person is no longer in the system at all and we need to clean stuff up.

$adtest = [bool] (Get-ADUser -Filter { SamAccountName -eq $input })

If they are in the system they could be a student and students are not going to be allowed access to GPO's so we need to remove them as owner. Eventually all GPO's will be changed to Domain Admins owned and upon creation it will default to the Domain Admins.


Solution

  • (Get-ADPrincipalGroupMembership -identity 12345 | select samaccountname).SamAccountName | ? {$_ -eq "Domain Admins" }
    
    # or 
    
    Get-ADPrincipalGroupMembership -identity 12345 | select samaccountname | ? {$_.samAccountName -eq "Domain Admins" }
    
    # Or Check the Domain Admins to see if Domain Admins contain the users you are looking for
    Get-ADGroupMember -Identity "Domain Admins" | ? { $_.name -eq 12345 }
    

    First example gives you the string response with name, "Domain Admins" if it exists.

    Second example gives you Object with SamAccountName property only since thats what you used in Select statement