Azure DevOps - Setting and Using Variables in PowerShell Scripts

后端 未结 2 982
既然无缘
既然无缘 2021-02-05 10:08

I have an Azure DevOps build pipeline that has two separate PowerShell scripts. In the first script, I am getting a value from an XML file and setting that value in an environme

相关标签:
2条回答
  • 2021-02-05 10:20

    Script 1

    Use quotes when setting the environment variable via task.setvariable since # signifies a PowerShell comment. You have commented out the string you intend to output.

    Also note that the environment variable may not be available in the script where you set it since the pipeline must first process task.setvariable in the output.

    $myXml = [xml](Get-Content ./MyXml.xml)  
    $departmentId = $myXml.Department.Id
    
    Write-Host "##vso[task.setvariable variable=DepartmentId;]$departmentId"
    Write-Host "Set environment variable to ($env:DepartmentId)"
    
    Get-ChildItem Env:
    
    Write-Host "Department Id ($departmentId)"
    

    Script 2

    You must still reference variables via $ inside an expression. You're missing $ before env.

    Write-Host "Using Department: $($env:DepartmentId)"
    
    0 讨论(0)
  • 2021-02-05 10:29

    To set environmental variables you need to set it using

    $env:departmentId = $myXml.Department.Id
    

    When using variables within strings you still need the $ sign in front of variables. As in

    Write-Host "Using Department: $($env:DepartmentId)"
    

    The reason environmental variables look different for get-childItem is that you are actually listing a psprovider, not the accessing the variable.

    Get-ChildItem Env:
    

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-6

    0 讨论(0)
提交回复
热议问题