Is it possible to call a PowerShell command directly in the pipelines groovy script? While using custom jobs in Jenkins I am able to call the command with the PowerShell Plugin. But there is no snippet to use this in the groovy script.
I also tried sh()
but it seems that this command does not allow multiple lines and comments inside the command.
Jenkins PowerShell PluginIntegrates with PowerShell by allowing you to directly write PowerShell scripts into the text box in Jenkins. Other than that, this plugin works pretty much like the standard shell script support.
msc and right click on Jenkins. Then click Properties , go to Logon tab, check mark This account and enter username and password which has admin privileges. Stop and Start Jenkins service. From now on when you will run powershell commands in Jenkins, they will be run as administrator.
Here's a simple PowerShell example. $eggs = 10 if ($eggs -lt 12) { "You have less than a dozen eggs." } In this example, we created a variable called $eggs and gave it a value of 10. Next, we set a conditional statement that says if $eggs is less than 12, display a message.
To call a PowerShell script from the Groovy-Script:
bat
command.errorlevel
) variable will be correctly returned (EXIT 1
should resulting in a FAILED
job).$LastExitCode
will be considered.Since Jenkins 2.207 with Powershell plugin 1.4, I have replace all my calls with the official powershell pipeline command. I do now recommend to use it. Note that you must predent
\$ErrorActionPreference='Stop';
to your Script if you want it to abort on Write-Error because of an Issue with the powershell plugin.
For that porpuse I have written a little groovy method which could be integrate in any pipeline-script:
def PowerShell(psCmd) {
psCmd=psCmd.replaceAll("%", "%%")
bat "powershell.exe -NonInteractive -ExecutionPolicy Bypass -Command \"\$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$psCmd;EXIT \$global:LastExitCode\""
}
[EDIT] I have added the UTF8 OutputEncoding: works great with Server 2016 and Win10.[/EDIT] [EDIT] I have added the '%' mask[/EDIT]
In your Pipeline-Script you could then call your Script like this:
stage ('Call Powershell Script')
{
node ('MyWindowsSlave') {
PowerShell(". '.\\disk-usage.ps1'")
}
}
The best thing with that method, is that you may call CmdLet
without having to do this in the Script, which is best-praxis.
Call ps1 to define CmdLet
, an then call the CmdLet
PowerShell(". '.\\disk-usage.ps1'; du -Verbose")
.
to be sure your step failed when the script return an error code (should be preferred), use &
if you don't care about it.Calling PowerShell scripts is now supported with powershell
step as announced on Jenkins blog.
The documentation mentions it supports multiple lines scripts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With