Your code is almost correct; you need to change your filter a little bit. When I tested this, it turns out that what I needed to do was treat the filter as a string, rather than a scriptblock:
$users = @"
upn;
user1@contoso.com
user2@contoso.com
"@ | Convertfrom-csv -Delimiter ";"
Foreach ($user in $users){
Get-ADUser -Filter "UserPrincipalName -eq '$($user.upn)'" -Properties name, samaccountname | select name, samaccountname
}
Note also that when accessing a member of an object stored in a variable embedded in a string, you need to explicitly include the evaluation operation $()
, thus the $($user.upn)
instead of just $user.upn
.