Best practice to run PowerShell scripts from Jenkins
Step-by-step
Choose “Execute Windows batch command”.
Paste this to print out command-lines itself to the console:
@echo off type %0 echo.
- Surround your PowerShell script like this:
powershell -noprofile -command "$ErrorActionPreference = 'Stop'; Set-PsDebug -Strict; .\Do-YourJob.ps1"
- If your script contains external commands (like
.exe
s or.cmd
s), test each exit code of them by$LASTEXITCODE
:
bcp.exe blah blah if ($LASTEXITCODE -ne 0) throw "bcp exit with $LASTEXITCODE"
Explanations
$ErrorActionPreference = 'Stop'
makes powershell.exe
exit with non-zero when an exception is thrown in the script (maybe).
Set-PsDebug -Strict
causes an exception when a variable is used before its assignment, otherwise an uninitialized variable results $null
.
Usually powershell.exe
returns zero exit code (means success in Jenkins) even if the last command exit with non-zero (means failure).
The PowerShell plugin allows you to write PowerShell codes directly but I thought it would be hard to catch some kind of errors. Probably due to its invocation i.e.:
powershell.exe "& 'C:\Windows\TEMP\hudson########.ps1'"