I am looking to find a way to write the Object ID of a user to a variable automatically via AzureAD.

Get-AzureAdUser -ObjectId "[email protected]"

will give the output of the ObjectId, DisplayName, UPN, UserType

I am looking to the write the ObjectId of the user (e.g qwert_1232_trwwqe) to variable such as $UserId for use further in the script.

1 Answers

0
mklement0 On Best Solutions

Lee Dailey provides a good pointer:

the usual way is to keep things in the $Var and simply address the properties when needed. So, assign the call to a $Var and get the value with $Var.ObjectID.

That said, if you do want to store the object ID alone in a dedicated variable, simply access the .ObjectId property on the object returned by Get-AzureAdUser:

$userId = (Get-AzureAdUser -ObjectId '[email protected]').ObjectId

In a follow-up comment you mention arriving at:

$Var = Get-AzureAdUser -ObjectId "[email protected]" | Select ObjectId

However, this use of the Select-Object cmdlet (whose built-in alias is select) is virtually pointless, as this still returns a (new, custom) object that requires you to access its .ObjectId property in order to retrieve the object ID value - and for that you could have just assigned the object returned by Get-AzureAdUser directly to $Var, as Lee suggests.

It is possible to use Select-Object to extract a single property value, namely via the
-ExpandProperty <propertyName> parameter
:

$Var = Get-AzureAdUser -ObjectId '[email protected]' | Select -ExpandProperty ObjectId

However, the (...).ObjectId syntax (dot notation) is not only more convenient, but also faster - and it even works on multiple objects (in PSv3+), in which case an array of values is returned (a feature called member enumeration).

In short, Select-Object -ExpandProperty is only needed if you're processing very large collections that must be processed one by one in the pipeline.