1

How to find aduser samaccountname by their upn?

$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
   }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ak2595
  • 301
  • 1
  • 3
  • 16
  • @Olaf - This didn't work for me; `Get-ADUser -ID «my-UPN»` threw an error `Get-ADUser: Cannot find an object with identity «my-UPN» under 'DC=...` – Jeff Zeitlin Sep 02 '22 at 18:22
  • @Olaf - not quite; see the answer below. Single-inside-double works; double-inside-single doesn't - I suspect that it's because _normally_ single-quoting a string is specifically done to prevent evaluation of stuff inside the string. – Jeff Zeitlin Sep 02 '22 at 18:33
  • 2
    While seductively convenient, the use of script blocks (`{ ... }`) as `-Filter` arguments is conceptually problematic and can lead to misconceptions. Here, it is the attempt to access a _property_ on variable `$user` that causes the problem. Jeff Zeitlin's answer provides an effective solution. See the linked duplicate for more information. – mklement0 Sep 02 '22 at 18:59
  • 1
    I should note that even though I have earned most of my [SO] 'rep' on Powershell answers, I consider @mklement0 to be far more knowledgeable about it than I am, and I have learned quite a bit from his answers and comments, such as his answer to the linked duplicate. If he says something, pay close attention. – Jeff Zeitlin Sep 02 '22 at 19:54

1 Answers1

1

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.

Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33