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
}
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With