3

I have a Powershell script which I run in an ADO release stage via the Powershell Task file path method (the ps1 file is in my wwwroot/scripts folder).

In the Powershell script, I need to access the Build.BuildId to do some work, however, it's blowing up on that variable wherein before when I ran this code via the "inline" method, it worked fine.

I cannot run the script "inline" as we have this script doing a lot of things and it exceeds the Powershell Task inline script character limit.

How can I access the Build.BuildId variable from the file?

 Build.BuildId : The term 'Build.BuildId' is not recognized as the name of a cmdlet, function, script file, or operable 
2022-02-16T18:58:30.4256566Z program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2022-02-16T18:58:30.4257898Z At D:\_agent1\_work\r11\a\...\wwwroot\scripts\myscript.ps1:70 char:90
2022-02-16T18:58:30.4259534Z + ...$project/_apis/build/builds/$(Build.BuildId)/workit ...

2 Answers 2

6

The name is upper-cased, and the . is replaced with the _

  • PowerShell script: $env:VARIABLE_NAME $env:BUILD_BUILDID

REF: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#environment-variables

Sign up to request clarification or add additional context in comments.

1 Comment

so my script file should have this: $buildId = $env:BUILD_BUILDID and then i can access $buildId
3

Powershell script Parameters aka arguments

Define a parameter at the top of your powershell script:

param( 
  [string] $buildId
)
Write-Host "The build id is $buildId";

and in the pipeline, add an argument to submit a value for that parameter in your powershell task

- task: PowerShell@2
  inputs:
    targetType: filePath
    filePath: /wwwroot/scripts/myscript.ps1
    arguments: -buildId $(Build.BuildId)

Parameters are better for this than environment variables, for a number of reasons:

  1. the script is explicit about what input it needs
  2. the pipeline is explicit about what input it is supplying
  3. you can easily run the script locally (e.g. for testing), supplying a suitable value to each parameter
  4. you can add parameter attributes, for example you can explicitly make a parameter mandatory, or give it a default value

1 Comment

Thanks, i ended up implementing it just fine with the other answer. $buildId = $env:BUILD_BUILDID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.