Jenkins: run PowerShell scripts

To complete the tutorial on Jenkins where I explain how to use it to run scheduled tasks and therefore turn it into a scheduler, I will show you in this tutorial, how to run PowerShell scripts.

The Double-Hop Problem

If you followed the first tutorial, I showed you how to run “simple” PowerShell cmdlets.

If you want to run more complex commands or scripts, you are faced with the Double-Hop problem, this problem is not related to Jenkins but to the use of remote session in PowerShell.

If you want more information on this subject, I invite you to read this article. : PowerShell Remoting and the “Double-Hop” Problem – Microsoft Tech Community

To solve this problem, you have to place an order on the Jenkins server:

Enable-WSManCredSSP -Role Client -DelegateComputer *

On each server where you want to run PowerShell scripts, you must pass the following command:

Enable-WSManCredSSP -Role Server

Run PowerShell scripts with Invoke-Command with Jenkins

Now we will see how to run PowerShell scripts using the command Invoke-Command.

Depending on the parameter pass to the Invoke-Command cmdlet we can:

  • Execute a script block for this you have to use the parameter-ScriptBlock.
  • Execute a .ps1 file which contains the script, you must use the parameter -FilePath.

Before showing you in Jenkins how to do this, here is how the code will appear.

Whether for a script block or a file, you must first declare the remote connection:

Below is a script block:

As you can see, after Invoke-Command, we use the -ScriptBlock parameter, then the PowerShell code and we end with the -Session parameter which takes the variable containing the remote session $RemoteSession.

To run a PowerShell script (.ps1), drop the file on the Jenkins server and then use Invoke-Commad to run the script.

As you can see, after Invoke-Command, we use the -FilePath parameter, which takes as value the location of the script on the Jenkins server and we end with the -Session parameter which takes the variable containing the remote session $RemoteSession.

So that you can imagine in Jenkins what it looks like here is a screenshot of a script block and a script in .ps1 format. . In the Build part, you must configure a PowerShell command.


You now know how to run “complex” PowerShell scripts with Jenkins.




Leave a Comment