I am running get-mguser to validate the account status in Azure from powershell. However when running for accounts with some special characters, like "&", "(", ")" it is throwing error. How can I fix this?
Script:
$Account_disabled =((get-mguser -UserID ABC&CD@[email protected] -Property accountEnabled | select accountEnabled).AccountEnabled -eq $false)
Error:
get-mguser : Bad request. Please fix the request before retrying.
Status: 400 (BadRequest)
ErrorCode: Request_BadRequest
I am running get-mguser to validate the account status in Azure from powershell. However when running for accounts with some special characters, like "&", "(", ")" it is throwing error. How can I fix this?
Script:
$Account_disabled =((get-mguser -UserID ABC&CD@[email protected] -Property accountEnabled | select accountEnabled).AccountEnabled -eq $false)
Error:
get-mguser : Bad request. Please fix the request before retrying.
Status: 400 (BadRequest)
ErrorCode: Request_BadRequest
2 Answers
Reset to default 0Just use single quotes:
$Account_disabled = ((get-mguser -UserID 'ABC&CD@[email protected]' -Property accountEnabled | select accountEnabled).AccountEnabled -eq $false)
You can still try to escape special characters using backtick (`) but it is not recommended in these cases:
$Account_disabled = ((get-mguser -UserID ABC`&CD@[email protected] -Property accountEnabled | select accountEnabled).AccountEnabled -eq $false)
Strange you have a user with &
as it isn't an allowed character for UserPrincipalName, see Username policies.
In the case you do, special characters such us &
have to be Url encoded. You can try HttpUtility.UrlEncode
for this.
# Only required if PowerShell 5.1
Add-Type -AssemblyNamer System.Web
# Only the name part of the UPN needs to be encoded
$id = [System.Web.HttpUtility]::UrlEncode('ABC&CD') + '@domain.onmicrosoft'
$Account_disabled = -not (Get-MgUser -UserID $id -Property accountEnabled).accountEnabled
It's likely that ABC&CD
is the user's DisplayName, in which case &
would be allowed and the cmdlet by itself performs the Url encoding for you. You could try using the -Filter
in that case:
$user = Get-MgUser -Filter "displayName eq 'ABC&CD'" -Property accountEnabled
&
,(
,)
- are all part of powershell's language / syntax so you can't use them in "BareWord" (i.e. unquoted) strings as they'll be interpreted as code rather than strings. You'll need to quote them with single or double quotes. – mclayton Commented Mar 7 at 13:37