Forum Discussion

charlie4872's avatar
charlie4872
Copper Contributor
Apr 14, 2021

Get Userprincipalname to use as second variable

Hello I am trying to use get-aduser and then extract the userprincipalname for use in a second command in a PS script. However it is not working as expected. Can anyone help as to why this is not working? Here is what I have.

$user = read-host 'Enter Username'
$UPN = get-aduser -identity $user |select-object UserPrincipalName
get-aduser $user -properties * |select PasswordLastSet
get-msoluser -userprincipalname $UPN |select LastPasswordChangeTimestamp

Im trying to compare password changes from on prem and Azure in one script. Any help is appreciated.

Thanks!

7 Replies

  • JaksaSkelin's avatar
    JaksaSkelin
    Copper Contributor
    The command is correct. What happens when you enter get-msoluser -userprincipalname username@domain.com directly without script
    • charlie4872's avatar
      charlie4872
      Copper Contributor
      When I use get-msoluser -userprincipalname user@domain.com | select-object LastPasswordChangeTimestamp by itself I get the output with just the date of the last password change as expected.

      When I adjust the commands as you suggested there is no error now (improvement) but it only returns the password change time for the Get-Aduser portion of the script and nothing from the get-msoluser portion of it. Very strange. Thanks again for your help.
      • JaksaSkelin's avatar
        JaksaSkelin
        Copper Contributor

        charlie4872 

        Can you output the content of the $UPN variable, maybe like this:

        $user = read-host 'Enter Username'
        $UPN = get-aduser -identity $user | select-object -expand UserPrincipalName
        get-aduser $user -properties * |select PasswordLastSet
        Write-Host "[$UPN]"
        get-msoluser -userprincipalname $UPN |select LastPasswordChangeTimestamp
  • JaksaSkelin's avatar
    JaksaSkelin
    Copper Contributor

    charlie4872 
    The command $UPN = get-aduser -identity $user | select-object UserPrincipalName does not return a string, it returns an object with the propery UserPrincipalName. You need to adjust the second call as follows: get-msoluser -userprincipalname $UPN.UserPrincipalName | select LastPasswordChangeTimestamp

    Alternatively you can also fetch UserPrincipalName as string: $UPN = get-aduser -identity $user | select-object -expand UserPrincipalName

    • charlie4872's avatar
      charlie4872
      Copper Contributor
      Hello JaksaSkelin thanks for the response! I have tried what you suggested and although I don't get an error in PS now, it appears to only returning just the results of the "PasswordLastSet" from the Get-Aduser and not the results of the Get-Msoluser "LastPasswordChangeTimestamp". Any idea why the actual results of the Get-Msoluser command don't appear?

      Thanks!

Resources