Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering multiple users with get-aduser

I'm new to powershell and have to fetch users from AD based on a list with names. Is there any way to filter from AD using something similar to an in-statement in SQL? (select * from users where name in ('Joe','Bill)?

As for now I fetch users in a foreach loop and add them to an arraylist, but I don't know if this is good practice:

function GetUsers()
{
$dummydata = @('Bill','Joe','Sam')
$users = New-Object System.Collections.ArrayList($null)

foreach($user in $dummydata)
{
 $aduser = get-aduser -f {GivenName -eq $user} -Properties * | select *
  $users.add($aduser) | Out-Null
}

Return ,$users

}
like image 473
Thomas B Avatar asked Mar 07 '13 10:03

Thomas B


2 Answers

You'd probably want to put this into a function:

$dummydata = @('Bill','Joe','Sam')

$filter = 
[scriptblock]::create(($dummydata| foreach {"(GivenName -eq '$_')"}) -join ' -or ')
Get-ADUser -f $filter
like image 76
mjolinor Avatar answered Nov 15 '22 12:11

mjolinor


mjolinor's answer is elegant and works, but the use of script blocks is problematic for two reasons:

  • It is unnecessary, because the script block will invariably be converted back to a string when it is passed to Get-ADUser -Filter.

  • More importantly, it perpetuates the widespread misconception that Get-ADUser -Filter accepts PowerShell script blocks that support PowerShell syntax, which is not true; it is a misconception that leads to frustration sooner or later; in short: construct your -Filter arguments as strings to begin with, and know that these filter strings, while resembling PowerShell syntax, use AD-provider-specific syntax, which is not only much more limited, but behaves subtly differently even with operators of the same name as in PowerShell - see this answer for the full story.

Therefore, use string manipulation to construct your filter:

Get-AdUser -Filter ('Bill', 'Joe', 'Sam' -replace 
                      '^.*', 'GivenName -eq "$&"' -join ' -or ')

For information on the regex-based -replace operator, see this answer.

The -Filter argument evaluates to the following string literal, which is what the AD provider ultimately sees:

GivenName -eq "Bill" -or GivenName -eq "Joe" -or GivenName -eq "Sam"
like image 5
mklement0 Avatar answered Nov 15 '22 10:11

mklement0