Get Userprincipalname to use as second variable

Brass Contributor

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

@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

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!
The command is correct. What happens when you enter get-msoluser -userprincipalname username@domain.com directly without script
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.

@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
Thanks for the reply JaksaSkelin. Using that I get the same results only this time it writes the UPN to the screen like below but no LastPasswordChangeTimestamp results. Here is what comes back

username@domain.com
PasswordLastSet
------------------
2/17/2020 8:05:09 AM

So only the AD user password details get displayed not the password details from mosoluser. No errors though so I cant tell what the issue may be.

Thanks again!
what is the output from
get-msoluser -userprincipalname user@domain.com | fl