azure - Azure Devops 中的 Invoke-Restmethod powershell - 奇怪的 powershell 错误

标签 azure powershell azure-devops azure-keyvault

我正在使用这个invoke-rest方法,这样我可以获得一个 token ,这样我就可以做一些sql工作。变量来自 Azure Key Vault。我尝试将变量写为

$($SPNAppid)
$SPNAppid
${$SPNAppid} etc

这是代码:

$request = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/${$TenantId}"/oauth2/token" -Body @{ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=${$SPNAppid}; client_secret=${$SPNValue} } -ContentType "application/x-www-form-urlencoded"

出现以下错误。执行此操作的最佳方法是什么 - 无论我做什么,我都会收到以下错误。

Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to 
delimit the name.
At C:\agent01_2\_work\_temp\b3f54d23-b7b6-4cc3-96ec-8b4b534be571.ps1:20 char:319
+ ... ervicePrincipalKey } -ContentType "application/x-www-form-urlencoded"
+                                                                         ~
The string is missing the terminator: ".

最佳答案

您发布的代码有一个额外的 " ,考虑到长行的歧义,我建议使用如下所示的splatting:

$header = @{
    "Content-type"  = "application/x-www-form-urlencoded"
    "Authorization" = "Bearer $token"
}

$body = @{ 
    resource      = "https://database.windows.net/"
    grant_type    = "client_credentials"
    client_id     = $SPNAppid
    client_secret = $SPNValue
} 

$params = @{
    Method      = 'Post'
    Uri         = "https://login.microsoftonline.com/$($TenantId)/oauth2/token"
    Body        = $body
    ContentType = $header
}

$request = Invoke-RestMethod @params

我认为 API 调用不会以这种方式工作,通常 clientId 等是 URL 的一部分,您可以在此处阅读更多相关信息 - https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow

关于azure - Azure Devops 中的 Invoke-Restmethod powershell - 奇怪的 powershell 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71703685/

相关文章:

azure - 使用Puppet将Azure客户端安装到所有节点

PowerShell 将 blob 文本上传到 Azure 时出错 : UploadText(string)

json - 具有/JSON正文的Powershell Invoke-Webrequest-无法反序列化吗?

powershell - 使用 System.IO.FileSystemWatcher 后使用 Powershell 循环文件

azure - Azure APIM 产品在无需订阅的情况下如何与多个产品配合?

azure - 当 Azure 区域丢失时,Azure 资源组会发生什么情况?

azure - 有没有办法以编程方式更改 cosmos db 表上的 TTL

tfs - VSTS/TFS 扩展 - 在不刷新整个页面的情况下反射(reflect)网格/板的变化

azure - 如何从 Azure Databricks 导出 MLFlow 模型作为 CD 阶段的 Azure DevOps 工件?

azure-devops - 在 VSTS Wiki 中嵌入 gif