如何通过Azure DevOps中的Powershell任务循环遍历数组参数

huangapple go评论59阅读模式
英文:

How to loop through array parameter via Powershell task in Azure DevOps

问题

我有一个参数,其中包含两个可执行文件的路径,并且我想要循环遍历它以对每个可执行文件进行签名。为此,我在Azure DevOps中使用了一个通过模板传递的PowerShell@2任务。

我似乎无法正确地通过我在模板代码中尝试的任何方法循环遍历可执行文件数组。

如何最好地循环遍历数组参数?感谢您的帮助。

这是我的最新代码:

parameters:
- name: executableList
  type: object
  default: []

steps:
- task: PowerShell@2
  displayName: 'Sign executables'
  inputs:
    targetType: 'inline'
    script: |
      # ...更多代码
      foreach ($executable in ${{ parameters.executableList }}) {
        & $signingExecutable sign /sm /s My /n "Sign Text" /tr http://rfc3161timestamp.globalsign.com/advanced /td sha256 /fd sha256 "$($Pipeline.Workspace)$executable"
      }      

错误:在扫描简单键时,找不到预期的冒号。

英文:

I have a parameter that consists of two executable paths and I want to loop through it to sign each executable. For this, I use a PowerShell@2 task that is passed via a template in Azure DevOps.

I don't seem to loop correctly through the executable array via any of the methods I've tried in my template code.

What is the best way to loop through the array parameter? Thanks for your help.

Here is my latest code:

parameters:
- name: executableList
  type: object
  default: []

steps:
- task: PowerShell@2
  displayName: 'Sign executables'
  inputs:
    targetType: 'inline'
    script: |
      #...more code here
          ${{ foreach (executable in  parameters.executableList) }} {
            & $signingExecutable sign /sm /s My /n "Sign Text" /tr http://rfc3161timestamp.globalsign.com/advanced /td sha256 /fd sha256 "$(Pipeline.Workspace)$executable"
          }

Error: While scanning a simple key, could not find expected ':'.

答案1

得分: 0

你可以尝试使用convertToJson函数。以下是一个小例子:

parameters:
- name: myArray
  type: object
  default:
  - "1"
  - "2"
  - "4"
  - "8"
  - "16"

steps:
- task: PowerShell@2
  displayName: 'Sign executables'
  inputs:
    targetType: 'inline'
    script: |
     $mayarrstr= @"
     ${{ convertToJson(parameters.myArray) }}
     "@
     $myarr = ConvertFrom-Json $mayarrstr
     
     foreach ($myvalue in $myarr)
     {
       Write-Host "Value: " $myvalue
     }     
英文:

You can try convertToJson function. Small example:

parameters:
- name: myArray
  type: object
  default: 
  - "1"
  - "2"
  - "4"
  - "8"
  - "16"

steps:
- task: PowerShell@2
  displayName: 'Sign executables'
  inputs:
    targetType: 'inline'
    script: |
     $mayarrstr= @"
     ${{ convertToJson(parameters.myArray) }}
     "@
     $myarr = ConvertFrom-Json $mayarrstr
     
     foreach ($myvalue in $myarr)
     {
       Write-Host "Value: " $myvalue
     }

huangapple
  • 本文由 发表于 2023年2月6日 20:22:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定