我正在使用这个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/