0

I need to write a Powershell Script to list the users name in specific OU+ the Groups in which the user belongs to (but I need to list specific Group and not to see all Groups).

Ex : OU : A

Users under OU A

they are Member to the Groups X Y Z ...

I have found this one :

Get-ADUser -Filter * -Properties samaccountname,memberof,description -SearchBase "OU" | 
 
foreach {
 
  $sam = $_.samaccountname
  $description = $_.description
 

  foreach ($group in $_.memberof) {
 
    New-Object PSObject -Property @{
 
      UserName = $_.samaccountname;
      Desc = $_.description
      
     Group = ($group -split ",")[0].Substring(3) 
 
    }
 
  }
 
} |select  username,Desc,Group 

But it will list all Groups to the user and I want to show all users and their Groups (but not all Groups just y x)

I want to list all user name in OU A and the Groups (but I want to see just Group y x) Can Some one help me please ?

Thanks

Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89

1 Answers1

0

Two ways:

  • a Where-Object clause in your second Foreach
  • an If statement inside that Foreach

Such as:

foreach ($group in ($_.memberof | where {$_ -match 'whatever'})) { …

Or

foreach ($group in $_.memberof) {
    if ($group -match 'whatever') {
        # create a PSCustomobject if you're using v3+
        [pscustomobject]@{

        }
    }
}

Also, I highly recommend collecting your AD users into a variable first rather than just pipelining it.

$users = get-aduser …
foreach ($u in $users) { …

It's a lot easier to keep track of what you're modifying at any point that way.

LeeM
  • 1,388
  • 9
  • 14