Executing powershell command directly in jenkins pipeline

后端 未结 4 1799
闹比i
闹比i 2020-12-05 03:15

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 Plu

相关标签:
4条回答
  • 2020-12-05 04:04

    From version 2.28 of Pipeline Nodes and Processes Plugin, we can directly use 'powershell'.

    Eg: powershell(". '.Test.ps1'") 
    
    0 讨论(0)
  • 2020-12-05 04:11

    You can use the sh command like this:

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

    Comments are supported in here.

    0 讨论(0)
  • 2020-12-05 04:13

    To call a PowerShell script 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.
    • I have notice that the 'powershell' is now available in pipeline, but since it have several issues I prefer this variant. Still waiting it works stabil. I actually have an issue with the 'dontKillMe' behavior.

    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.

    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")
    
    • 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.
    0 讨论(0)
  • 2020-12-05 04:15

    Calling PowerShell scripts is now supported with powershell step as announced on Jenkins blog.

    The documentation mentions it supports multiple lines scripts.

    0 讨论(0)
提交回复
热议问题