【问题标题】:Azure DevOps Get Current User ObjectIdAzure DevOps 获取当前用户 ObjectId
【发布时间】:2019-06-18 18:36:52
【问题描述】:

有没有办法获取当前在 Azure DevOps 中执行 Azure PowerShell 任务的服务主体的 ObjectId?

我正在创建一个资源,然后想为“当前”用户应用权限..但不知道如何获取当前用户 ObjectId / ApplicationId

这可能吗?

【问题讨论】:

  • 你找到方法了吗?
  • 嗨@dr0pdb,看看我刚刚发布的答案????。

标签: powershell azure-devops


【解决方案1】:

好的 - 基于上述,我做了一个小功能 - 它可能适用于很多情况:


function Get-CurrentUserObjectID {
    $ctx = Get-AzContext

    #This is different for users that are internal vs external
    #We can use Mail for users and guests
    $User = Get-AzADUser -Mail $ctx.Account.id
    if (-not $user) {  #Try UPN
        $User = Get-AzADUser -UserPrincipalName $ctx.Account.Id
    }
    if (-not $User) { #User was not found by mail or UPN, try MailNick
        $mail = ($ctx.Account.id -replace "@","_" ) + "#EXT#"
        $User = Get-AzADUser | Where-Object { $_MailNick -EQ $Mail}
    }

    Return $User.id
}

【讨论】:

  • 是的,这是一个相当不错的实现,我肯定会窃取它?
  • 也会将此标记为答案,因为它比我的闲聊要简洁得多??
【解决方案2】:

根据是用户还是服务主体,似乎有两种方法:-

Get-AzADUser
Get-AzADServicePrincipal

我相信这些在Az.Resources 模块中。因此,为了给您 ObjectId(用于权限),您可以采取如下两步方法:

$x = (Get-AzContext).Account.Id
$x
> df6fc4f6-cb05-4301-91e3-11d93d7fd43d # ApplicationId

$y = Get-AzADServicePrincipal -ApplicationId $x
$y.Id
> c3588e6a-b48b-4111-8241-3d6bd726ca40 # ObjectId

我无法让标准用户可靠工作。如果您的用户是直接在 AzureAD 中创建的,而不是外部的(即 gmail.com、outlook.com 等)这应该工作:

$x = (Get-AzContext).Account.Id
$x
> sample@your-domain.onmicrosoft.com # UserPrincipalName

$y = Get-AzADUser -UserPrincipalName $x
$y.Id
> c5d4339b-48dc-4190-b9fb-f5397053844b # ObjectId

如果您的用户是外部用户,并且具有奇怪的 your.email.address_outlook.com#EXT#@your-domain.onmicrosoft.comUserPrincipalName,我认为您需要通过一些字符串操作来解决这个问题 ?。

但是!无论如何,您不应该使用用户帐户编写脚本,所以这可能无关紧要 ?。

注意:我没有在 Azure DevOps 中尝试过,您可能需要升级 PowerShell 包,但我认为 Get-AzureRmADUser 和 Get-AzureRmADServicePrincipal 应该存在相同的命令。请告诉我。

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多