RedMageKnight
RedMageKnight

Reputation: 187

Get-Msoluser accepts a hardcoded string but not a variable for parameter UserPrincipalName

I'm going a little batty because I can't think of anything I'm doing wrong with this code snippet. I'm literally just trying to get a single user using Get-MsolUser using the parameter -UserPrincipalName in the following line:

$usr = Get-MsolUser -UserPrincipalName $wantedUser

I'm calling this code from within a function that originally had the $wantedUser variable as a parameter, but due to the issues I'm experiencing, I've tried to add it as a script variable, I've tried reassigning the parameter variable to a local function variable, but nothing works. I can put the raw user principal name in there like below:

$usr = Get-MsolUser -UserPrincipalName "[email protected]"

And it works... no problem. Queries and assigns the user information to the $usr variable as expected where the rest of my code logic works fine. I know I'm just probably stupidly looking over something simple, but for the life of me I can't figure it out. Can someone please shed some light on what I might be doing wrong? I know it's passing the value in there to some extent because I get an exception saying the following:

Get-MsolUser : User Not Found.  User: "[email protected]".
At C:\locationWhereMyScriptIsLocated.ps1:19 char:12
+     $usr = Get-MsolUser -UserPrincipalName $wantedUser
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [Get-MsolUser], MicrosoftOnlineException
    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UserNotFoundException,Microsoft.Online.Administration.Automation.GetUser

Upvotes: 1

Views: 470

Answers (1)

mklement0
mklement0

Reputation: 439277

I don't have access to Get-MsolUser, but from what I can tell, the error message Get-MsolUser : User Not Found. User: "[email protected]". suggests that the user name mistakenly contains embedded " chars. - that is, the verbatim value of $wantedUser may be "[email protected]" rather than the expected [email protected].

Thus, as a quick fix, try:

$usr = Get-MsolUser -UserPrincipalName ($wantedUser -replace '"')

But it's worth investigating why these embedded " characters ended up in $wantedUser to begin with, and perhaps eliminate the problem at the source.

Upvotes: 1

Related Questions