最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

powershell - Getting error while querying Azure (get-mguser) for users with special characters - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question edited Mar 7 at 14:01 Kartik M asked Mar 7 at 12:57 Kartik MKartik M 1093 silver badges10 bronze badges 1
  • The characters you've mentioned - &, (, ) - 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
Add a comment  | 

2 Answers 2

Reset to default 0

Just 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
发布评论

评论列表(0)

  1. 暂无评论