Error in script for resetting O365 user password

Hello,

Am trying to build a PS script to reset a user’s password in our O365 tenant. But it throws the following error:

“Set-AzureADUserPassword : Unexpected character encountered while parsing value: <. Path ‘’, line 0, position 0.”

Here is the script:

#Collect details of the User for whom password to be reset
$Username = Read-Host -Prompt “Enter the username”
$ObjectId = Get-AzureADUser -ObjectId $Username@domain.com
#Convert the default password to a Secure String
$SecPaswd = “Password” | ConvertTo-SecureString -AsPlainText -Force
#Reset the Password
Set-AzureADUserPassword -ObjectId $ObjectId -Password $SecPaswd -ForceChangePasswordNextLogin $true

Can someone please advise what could be going wrong?

This:

$ObjectId = Get-AzureADUser -ObjectId $Username@domain.com

Is your problem, I think.

$ObjectId = Get-AzureADUser -ObjectId "$($Username)@domain.com"

Might work. If you were to add some output showing what $ObjectId contains, it’d help you debug it. Errors like this are 100% because some variable doesn’t contain what you thought it did, and so you need to find out what it does contain :). There’s a lovely debugging chapter in Learn PowerShell Scripting in a Month of Lunches!

If you build the variable before you send it to a command, it’s easier to troubleshoot that you are sending what you think:

$prompt = Read-Host -Prompt "Enter the username"
$username = "{0}@domain.com" -f $prompt
"Attempting sign in as {0}" -f $username
...

Hi Don,

Tried your suggestion and received this error:

Set-AzureADUserPassword : Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
At …\ResetO365Password.ps1:12 char:1

  • Set-AzureADUserPassword -ObjectId "$ObjectId" -Password $SecPaswd -Fo …
  •   + CategoryInfo          : NotSpecified: (:) [Set-AzureADUserPassword], JsonReaderException
      + FullyQualifiedErrorId : Newtonsoft.Json.JsonReaderException,Microsoft.Open.AzureAD16.Graph.PowerShell.Custom.Cmd
     let.SetUserPassword</em>
    
    

I am newbie at PS so will definitely look up the reference book.

Figured it out…It was indeed the ObjectId variable which was causing the error. As you rightly said it contained something that the final command could not process correctly.

I have since modified the script like this and it now works:-

#Collect details of the User for whom password to be reset
$Username = Read-Host -Prompt "Enter the username"
#Convert the default password to a Secure String
$SecPaswd = "Password" | ConvertTo-SecureString -AsPlainText -Force
#Reset the Password
Set-AzureADUserPassword -ObjectId "$Username@domain.com" -Password $SecPaswd -ForceChangePasswordNextLogin $true