Using Azure DevOps Pipeline Variables in PowerShell Script Files

BEN ABT
medialesson
Published in
2 min readMar 17, 2023

Using Azure DevOps Pipeline Variables in PowerShell Script Files

Azure Pipelines inherently provides the ability for PowerShell scripts to be defined and executed inline.

- task: AzureCLI@2
displayName: Bicep apply
inputs:
azureSubscription: MyAzureDevOpsConnectionName
scriptType: pscore
scriptLocation: inlineScript
inlineScript: az deployment group create --resource-group $(AZ_PLATFORM_RESOURCE_GROUP_NAME) --name $(AZ_DEPLOYMENT_NAME)-$(AZ_ENV_NAME)

Unfortunately, this can become very confusing in many situations and also repetitive, since, for example, an Azure Bicep deployment task is required in several stages, so that the task is repeated accordingly.

It can help that the PowerShell script is no longer declared inline, but via a scriptPath.

- task: AzureCLI@2
displayName: Bicep apply
inputs:
azureSubscription: MyAzureDevOpsConnectionName
scriptType: pscore
scriptLocation: scriptPath
inlineScript: $(Pipeline.Workspace)/bicep/run.ps1

What the script is missing now are the variables, whereby one must note that by default variables are available only within the file. This means that the variable $(AZ_PLATFORM_RESOURCE_GROUP_NAME).

To make variables available from outside in a PowerShell script file you need the $ENV: prefix.

# run.ps1
az deployment group create `
--resource-group $($ENV:AZ_PLATFORM_RESOURCE_GROUP_NAME) `
--name "$($ENV:AZ_DEPLOYMENT_NAME)-$($ENV:AZ_ENV_NAME)"

Now you can clean up your pipeline YAML file and reuse PowerShell commands very easily.

Autor

Benjamin Abt

Ben is a passionate developer and software architect and especially focused on .NET, cloud and IoT. In his professional he works on high-scalable platforms for IoT and Industry 4.0 focused on the next generation of connected industry based on Azure and .NET. He runs the largest german-speaking C# forum myCSharp.de, is the founder of the Azure UserGroup Stuttgart, a co-organizer of the AzureSaturday, runs his blog, participates in open source projects, speaks at various conferences and user groups and also has a bit free time. He is a Microsoft MVP since 2015 for .NET and Azure.

Originally published at https://schwabencode.com on March 17, 2023.

--

--