Running powershell command directly in the jenkins pipe

Can I call the PowerShell command directly in the groovy script pipelines? When using custom jobs in Jenkins, I can invoke the command using the PowerShell plugin. But there is no fragment to use it in a groovy script.

I also tried sh() , but it seems that this command does not allow multiple lines and comments inside the command.

+11
powershell jenkins jenkins-plugins jenkins-pipeline
source share
3 answers

To invoke a PowerShell script from Groovy-Script:

  • You must use the bat command.
  • After that, you should be sure that the Error Code ( errorlevel ) variable will be returned correctly ( EXIT 1 should result in a FAILED error).
  • Finally, to be compatible with PowerShell-Plugin, you must be sure that $LastExitCode will be counted.
  • I noticed that "powershell" is now available in the pipeline, but since it has several problems, I prefer this option. Still waiting, working stably. I really have a problem with the behavior of dontKillMe.

For this part, I wrote a small method that can be integrated into 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 added UTF8 OutputEncoding: works great with Server 2016 and Win10. [/ EDIT] [EDIT] I added the mask '%' [/ EDIT]

Then, in your pipeline script, you can call your script like this:

 stage ('Call Powershell Script') { node ('MyWindowsSlave') { PowerShell(". '.\\disk-usage.ps1'") } } 

The best thing about this method is that you can call CmdLet without having to do it in CmdLet , which is best practice.

Call ps1 to define CmdLet , and then call CmdLet

 PowerShell(". '.\\disk-usage.ps1'; du -Verbose") 
  • Remember to use withEnv () and then you are better than fully compatible with the Powershell plugin.
  • put your script off . to make sure that your step failed when the script returns an error code (should be preferred), use & if it doesn't matter to you.
+22
source share

PowerShell scripting is now supported using the powershell step as announced on the Jenkins blog .

The documentation mentions that it supports multi-line scripts.

+13
source share

You can use the sh command as follows:

 sh """ echo 'foo' # bar echo 'hello' """ 

Comments can be found here.

-4
source share

All Articles