0

I am working on something to retrieve account information from a domain controller.

$Input = $InputBox1.Text

$InputBox10.Text = (Get-ADUser -Filter "UserPrincipalName -like '$Input'" -Server "server.com" -Properties UserPrincipalName | Select-Object @{Name='UPN'; Expression={if($Input -ne $_.UserPrincipalName){'No corresponding UPN'}else{$_.UserPrincipalName}}}).'UPN'

So if the account is in server.com I receive as output the UPN of that account, but if the account is not in server.com I want to receive 'No corresponding UPN' but instead receiving that output it's empty.

Any idea?

Thanks in advance.

Kind Regards, Ralph

Ralph
  • 49
  • 1
  • 1
  • 3
  • 2
    As aside, Don't use `$Input` as self-defined variable name, because it is an [Automatic variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7#input) – Theo Apr 08 '20 at 10:27
  • Aside from Theo's note, does this answer your question? [Why won't Variable update?](https://stackoverflow.com/questions/55403528/why-wont-variable-update) – iRon Apr 08 '20 at 10:32

1 Answers1

0

As commented, $Input is a wrong variable name because it is an Automatic variable. You should use something else for that.
Also, by trying to cram almost all of the code in a single line, you are bound to run into trouble. Just add an extra line so things become clearer:

$UpnInput = $InputBox1.Text

$user = Get-ADUser -Filter "UserPrincipalName -eq '$UpnInput'" -Server "server.com"
$InputBox10.Text = if ($user) { $user.UserPrincipalName } else { 'No corresponding UPN' }

Hope this helps

Get-ADUser by default returns these properties: DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName. If no user is found, it returns $null.

Theo
  • 57,719
  • 8
  • 24
  • 41
  • Thanks Theo! This was indeed the solution. Didn't know I could not use $Input. Good to know and will help a lot in future. – Ralph Apr 08 '20 at 10:40