Executing powershell command directly in jenkins pipeline

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 HTML Publisher Plugin 1.3 gives 404 error
  • Jenkins cannot read Github password since upgrading to Git client plugin 2.1.0
  • How do I trigger a Jenkins build of a single module in a multi-module Maven build from Subversion?
  • How can I know how long a Jenkins job has been in the wait queue after the job is finished?
  • Installing bundler within Jenkins docker image
  • Passing data between build steps in Jenkins
  • How can I create parameterized Jenkins job?
  • Configuring Geb and Spock on Jenkins (Grails)
  • Bash script running from launchDaemon on MAC - not connecting to jenkins
  • How to list all `env` properties within jenkins pipeline job?
  • Write a batch script to edit text in a .cs file
  • Gerrit Trigger on multiple SCM in jenkins not working
  • 2 Solutions collect form web for “Executing powershell command directly in jenkins pipeline”

    You can use the sh command like this:

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

    Comments are supported in here.

    To call a PowerScript from the Groovy-Script:

    • you have to use the bat command.
    • After that, you have to be sure that the Error Code (errorlevel) variable will be correctly returned (EXIT 1 should resulting in a FAILED job).
    • Last, to be compatible with the PowerShell-Plugin, you have to be sure that $LastExitCode will be considered.

    For that porpuse I have written a little groovy method which could be integrate in any pipeline-script:

    def PowerShell(psCmd) {
        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]

    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")
    • Do not forget to use withEnv() an then you are better than fully compatible with the Powershell plugin.
    • postpone your Script with . to be sure your step failed when the script return an error code (should be preferred), use & if you don’t care about it.
    Git Baby is a git and github fan, let's start git clone.