How to combine 2 "get-aduser" commands into one report

deniecegreenwood
deniecegreenwood used Ask the Experts™
on
Hello.  I have 2 pieces of information that I need to combine into one report.
First: list members of GROUPA and GROUPB
Second: list users in OU=THISOU.

As you can see, everything from "Select-Object" and down is the same for both.  I believe I just need to find how to combine the two Get-ADUser commands.  Thanks in Advance.

$UserExport =  Get-ADUser -Filter * -Properties memberOf | `
Where-Object {
    $_.memberof.contains('CN=GROUPA,OU=Groups,OU=HERE,OU=THERE,DC=ACME,DC=com') -or
    $_.memberof.contains('CN=GROUPB,OU=Groups,OU=HERE,OU=THERE,DC=ACME,DC=com')
    } |
    Select-Object -Property @{n="ColumnA"; e={"CUSTOM COLUMN"}}, SamAccountName, Surname, GivenName |
    sort SamAccountName |
  ConvertTo-CSV -NoTypeInformation |
  Select-object -Skip 1 |
  Set-Content -Path "C:\Scripts\Output\THESEGROUPS.csv"

_______________


$UserExport =  Get-ADUser -Filter * -SearchBase "OU=THISOU,OU=HERE,DC=ACME,DC=com" |
  Select-Object -Property @{n="ColumnA"; e={"CUSTOM COLUMN"}}, SamAccountName, Surname, GivenName |
  sort SamAccountName |
  ConvertTo-CSV -NoTypeInformation |
  Select-object -Skip 1 |
  Set-Content -Path "C:\Scripts\Output\THISOU.csv"
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Your first call to Get-ADUser is with -Filter * and no search base, so it's searching every user anyway. That means the second call is already a subset of the first.

Since you're piping to where-object to filter your results on the first call, the key is to just include a condition in the Where-Object block to include accounts that fall within the OU you want.

I believe an easy way to do that is to look at the distinguished name of the user, and do a -like compare to match the OU you want to the end of the DN, since a typical user name might be "CN=Some Guy,OU=THISOU,OU=HERE,DC=ACME,DC=com":

$UserExport =  Get-ADUser -Filter * -Properties memberOf | `
Where-Object {
    $_.memberof.contains('CN=GROUPA,OU=Groups,OU=HERE,OU=THERE,DC=ACME,DC=com') -or
    $_.memberof.contains('CN=GROUPB,OU=Groups,OU=HERE,OU=THERE,DC=ACME,DC=com') -or
    $_.DistinguishedName -ilike '*,OU=THISOU,OU=HERE,DC=ACME,DC=com'
    } |
    Select-Object -Property @{n="ColumnA"; e={"CUSTOM COLUMN"}}, SamAccountName, Surname, GivenName |
    sort SamAccountName |
  ConvertTo-CSV -NoTypeInformation |
  Select-object -Skip 1 |
  Set-Content -Path "C:\Scripts\Output\THESEGROUPS.csv"

Open in new window


Note that -ilike forces the case-insensitive version of -like. * is the wildcard character.

Author

Commented:
Outstanding!  Thank you so very much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial