Azure DevOps 获取当前用户的 ObjectId

3

是否有一种方法可以获取正在执行Azure DevOps中Azure PowerShell任务的服务主体的ObjectId?

我正在创建资源,然后想为“当前”用户应用权限..但无法弄清楚如何获取当前用户的ObjectId/ApplicationId。

这可能吗?

最初的回答:


你找到方法了吗? - undefined
嗨 @dr0pdb,看看我刚刚发布的答案。 - undefined
2个回答

3

根据上述内容,我已经编写了一个小函数-它可能适用于许多情况:


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
}

是的,说实话,这是一个相当不错的实施方案,我肯定会借鉴它。 - undefined
也会将此标记为答案,因为它比我废话更简洁。 - undefined

1

根据是用户还是服务主体,似乎有两种方法可以完成这个操作:

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

如果您的用户是外部用户,并且其 UserPrincipalName 是奇怪的 your.email.address_outlook.com#EXT#@your-domain.onmicrosoft.com,则您需要通过一些字符串操作来解决这个问题。
但是!您不应该使用用户帐户进行脚本编写,因此这可能并不重要。
注意:我在Azure DevOps中尚未尝试过此操作,您可能需要升级PowerShell软件包,但我认为相同的命令应存在,如Get-AzureRmADUser和Get-AzureRmADServicePrincipal。请告诉我。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接