Azure DevOps中PowerShell任务如何循环遍历数组参数
解决Azure DevOps模板中遍历可执行文件数组并签名的问题
错误原因
你将Azure DevOps的模板循环语法${{ foreach }}直接写入PowerShell脚本块的字符串中,YAML解析器会误将其识别为YAML结构的一部分,从而抛出While scanning a simple key, could not find expected ':'的语法错误。
两种可行解决方案
方案一:PowerShell内部遍历数组(推荐)
将YAML参数数组传递到PowerShell中,用PowerShell原生循环处理,支持复杂逻辑且避免路径空格问题:
parameters: - name: executableList type: object default: [] steps: - task: PowerShell@2 displayName: 'Sign executables' inputs: targetType: 'inline' script: | # 将YAML参数转换为PowerShell数组 $executables = '${{ convertToJson(parameters.executableList) }}' | ConvertFrom-Json foreach ($executable in $executables) { # 安全拼接路径,避免空格问题 $fullPath = Join-Path -Path $(Pipeline.Workspace) -ChildPath $executable & $signingExecutable sign /sm /s My /n "Sign Text" /tr http://rfc3161timestamp.globalsign.com/advanced /td sha256 /fd sha256 $fullPath }
方案二:YAML模板循环生成脚本行
通过Azure DevOps模板的each循环,在YAML层面直接生成多个签名命令行:
parameters: - name: executableList type: object default: [] steps: - task: PowerShell@2 displayName: 'Sign executables' inputs: targetType: 'inline' script: | #...more code here ${{ each 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 }}" }
方案选择
- 若需要在循环内添加错误处理、日志输出等复杂逻辑,优先选择方案一;
- 若仅需批量执行简单签名命令,方案二的YAML展开方式更直观。
内容的提问来源于stack exchange,提问作者intelligentparadise
相关产品推荐
相关产品推荐

