Running Powershell scripts using Jenkins

Jenkins has been primarily used for automating jobs and tasks on Linux servers. In this blog, we will be configuring Jenkins to execute Powershell scripts on Windows. This blog will not be covering Jenkins server set up steps on Windows. You can refer to the following link for Jenkins installation.

Running the Job:

Go to the Jenkins home page and execute the job just created. Executing the job will bring a form with the options provided in the parameters specified as in the image below:

Click Build.

That’s it. Once the job is complete. A new file named Second File gets created in C:\temp with content as This is a message from Jenkins!

Executing Powershell scripts/commands remotely

The above job creates a text file on the Jenkins server itself. To setup remote Powershell scripts we first need to configure Jenkins server for remote Powershell script execution. To enable remote Windows machine in to the WS-Man trusted list on Jenkins servers. Execute the below command on Powershell window on Jenkins server. The command will add all the remote machine to the trusted list.

Set-Item WSMan:\localhost\Client\TrustedHosts *

Along with the commands, we would also need to enable remote script execution also. To enable execution of Powershell scripts remotely execute the following command in Powershell window on Jenkins server.

Set-ExecutionPolicy RemoteSigned –Force

We will have to install a new plugin named EnvInject Plugin for transferring variables e.g. passwords.

# Configure build failure on errors on the remote machine similar to set -x on bash script
$ErrorActionPreference = 'Stop'
# Create a PSCredential Object using the "Username" and "Password" variables created on job
$Password = $env:Password | ConvertTo-SecureString -AsPlainText -Force
$creddentials = New-Object System.Management.Automation.PSCredential -ArgumentList $env:UserName, $Password
.
# It depends on the type of job you are executing on the remote machine as to if you want to use "-ErrorAction Stop" on your Invoke-Command.
Invoke-Command -ComputerName $env:Computer -Credential $credentials -ScriptBlock {
Restart-Service -Name W32Time
}

Run the build and check the Windows logs on remote computer specified to verify if the Windows Time service has got restarted.