Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Jenkins variable in my Powershell Script

I have written a simple script via PowerShell to gather some files and zip them into one folder, lets call it Script.ps1. I want to make the script run every time Jenkins does a new build, however I also would like the name of the zip file to be the BUILD_NUMBER.

How can I create a variable in PowerShell that is Jenkins's current build number? As of the moment I am calling the Script.ps1 in the execute shell section of configuration.

like image 565
Foster Avatar asked Jun 18 '14 17:06

Foster


People also ask

How do I run a variable in a PowerShell script?

Working with variables To create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .

How do I use Jenkins credentials in PowerShell script?

To use, first go to the Credentials link and add items of type Secret file and/or Secret text. Now in a freestyle job, check the box Use secret text(s) or file(s) and add some variable bindings which will use your credentials. The resulting environment variables can be accessed from shell script build steps and so on.

Can you use environment variables in PowerShell?

PowerShell can access and manage environment variables in any of the supported operating system platforms. The PowerShell environment provider lets you get, add, change, clear, and delete environment variables in the current console.


2 Answers

I'm not familiar with Jenkins, but I believe BUILD_NUMBER is an environment variable.

To access it in PowerShell, use $env:BUILD_NUMBER

E.g. If using 7-zip

7z.exe a "$env:BUILD_NUMBER.zip" C:\Build\Path  
like image 122
Rynant Avatar answered Sep 25 '22 23:09

Rynant


You can add arguments to your Script.ps1. Just use Param at the top of the script:

Param( $BuildNumber ) #must be first statement in script # your current script goes here 

then you can call the script passing BUILD_NUMBER as argument from Jenkins. Refer to this question for calling Powershell script with argument.

like image 36
tkokasih Avatar answered Sep 22 '22 23:09

tkokasih