Azure管道:在Powershell中设置和访问变量

时间:2020-09-17 21:09:20

标签: azure-devops azure-pipelines

在Azure管道中,我有一个Powershell任务(内联脚本),在其中设置了变量

Write-Host "##vso[task.setvariable variable=deployActivity]false"

此行之后,仅出于检查设置变量的目的,我具有以下powershell-

if ($(deployActivity) -eq $true) {
    Write-Host "deployActivity=true (bool)"
}

但是,此操作失败并显示以下错误:

deployActivity : The term 'deployActivity' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

问题-

  1. 在上面做什么,以获取变量-它正确/可能吗?还是只能在后续任务中引用变量
  2. 为什么会失败?在Powershell中引用变量是否需要其他语法?

请告诉我

谢谢

2 个答案:

答案 0 :(得分:1)

针对该命令,按documentation

在taskcontext的变量服务中设置变量。第一项任务 可以设置变量,随后的任务就可以使用该变量。 该变量作为环境暴露给以下任务 变量。

它仅在设置它之后的任务上可用。如果需要在同一脚本中引用该值,则应该已经知道内部变量应该是什么。

此示例YML适用于我:

# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml

trigger:
- master

pool:
  vmImage: 'windows-2019'

steps:

    
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Write-Host "##vso[task.setvariable variable=deployActivity]"Example string""'

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Write-Host "Deploy Activity: $(deployActivity)"'

第二个任务的输出:

Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Linux, macOS, or Windows
Version      : 2.170.1
Author       : Microsoft Corporation
Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
==============================================================================
Generating script.
========================== Starting Command Output ===========================
"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\3a04683f-6159-4bee-862b-2e899e977789.ps1'"
Deploy Activity:  Example string
Finishing: PowerShell

答案 1 :(得分:0)

尝试用""-"$(deployActivity)"包装变量:

if ("$(deployActivity)" -eq $true) {
    Write-Host "deployActivity=true (bool)"
}