首页 > windows > 将用户ObjectID写入变量#Powershell

将用户ObjectID写入变量#Powershell (Writing User ObjectID to variable #Powershell)

问题

我希望找到一种方法通过AzureAD自动将用户的对象ID写入变量。

Get-AzureAdUser -ObjectId“Contose@contoso.com”

将给出ObjectId,DisplayName,UPN,UserType的输出

我期待将用户的ObjectId(例如qwert_1232_trwwqe)写入变量,例如$ UserId,以便在脚本中进一步使用。

解决方法

Lee Dailey提供了一个很好的指针:

通常的方法是保留内容,$Var并在需要时简单地处理属性。因此,将调用分配给a $Var并获取值$Var.ObjectID

也就是说,如果您确实想要将对象ID 单独存储在专用变量中,只需访问.ObjectId返回的对象上的属性Get-AzureAdUser

$userId = (Get-AzureAdUser -ObjectId 'Contose@contoso.com').ObjectId

在后续评论中,您提到到达:

$Var = Get-AzureAdUser -ObjectId "Contose@contoso.com" | Select ObjectId

但是,使用Select-Objectcmdlet(其内置别名select)实际上是毫无意义的,因为这仍然会返回一个(新的,自定义的)对象,它要求您访问其.ObjectId 属性以便检索对象ID值 - 为此您可以只通过分配返回的对象Get-AzureAdUser 直接$Var,李建议。

能够使用Select-Object以提取一个单一的属性,即通过
-ExpandProperty <propertyName>参数

$Var = Get-AzureAdUser -ObjectId 'Contose@contoso.com' | Select -ExpandProperty ObjectId

但是,(...).ObjectId语法(点表示法)不仅更方便,而且更快 - 甚至可以在多个对象(在PSv3 +中)上工作,在这种情况下返回一个值数组(称为成员枚举的特征)。

简而言之,Select-Object -ExpandProperty只有在处理必须在管道中逐个处理的非常大的集合时才需要

问题

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

Get-AzureAdUser -ObjectId "Contose@contoso.com"

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.

解决方法

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 'Contose@contoso.com').ObjectId

In a follow-up comment you mention arriving at:

$Var = Get-AzureAdUser -ObjectId "Contose@contoso.com" | 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 'Contose@contoso.com' | 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.

相似信息