【问题标题】:How to write "System.Collections.Hashtable" variable in Azure DevOps PowerShell如何在 Azure DevOps PowerShell 中编写“System.Collections.Hashtable”变量
【发布时间】:2019-08-18 09:56:30
【问题描述】:

我有一个System.Collections.Hashtable 类型的变量,我想将此值写入 Powershell 脚本中的 azure DevOps 变量中,并且需要在以下任务中使用该变量。

在 azure DevOps 中创建的变量:header

任务 1

Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId $env:tenant_id
$head = $null
$head = @{}
$head = Get-PowerBIAccessToken
Write-Host ("##vso[task.setvariable variable=headers]$head")

任务 2

Write-Host "Header is " $env:headers

Invoke-RestMethod -Headers $env:headers -Uri 'https://api.powerbi.com/v1.0/myorg/groups'

但任务 2 中的问题是

标题是 System.Collections.Hashtable
调用-RestMethod:不能 绑定参数“标题”。无法转换 要键入的“System.String”类型的“System.Collections.Hashtable”值 “System.Collections.IDictionary”。

由于标头的值只是分配System.Collections.Hashtable的字符串而不是实际值

【问题讨论】:

  • 您是否尝试过使用 Get-PowerBIAccessToken 上的 -AsString 开关?这应该将访问令牌的值写入 $env:headers 变量而不是类型。然后您可以在任务 2 中构造哈希表
  • @NickGraham 很抱歉刚接触 PowerShell,您能否提供一个有关如何使用 -AsString 的示例。 ?
  • $head = Get-PowerBIAccessToken -AsString
  • 您可能会发现在同一任务中获取访问令牌和调用 Invoke-RestMethod 更容易
  • 您需要查看由 Get-PowerBIAccessToken 返回的哈希表的结构(没有 -AsString 开关)。然后创建一个具有相同属性的新哈希表。创建空哈希表$headers = @{}。然后添加属性$headers[“PropertyName”] = $env:headers

标签: powershell azure-devops hashtable


【解决方案1】:

如果您在同一任务中调用 Invoke-RestMethod,则可以避免将令牌写入 Azure DevOps 变量的复杂性。

Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId $env:tenant_id
$head = $null
$head = @{}
$head = Get-PowerBIAccessToken

Invoke-RestMethod -Headers $head -Uri 'https://api.powerbi.com/v1.0/myorg/groups' 

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2023-02-09
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多