Skip to content

Instantly share code, notes, and snippets.

@MiguelTVMS
Created May 25, 2017 00:29
Show Gist options
  • Save MiguelTVMS/02c85fb95181d01ca2997346e768bbbe to your computer and use it in GitHub Desktop.
Save MiguelTVMS/02c85fb95181d01ca2997346e768bbbe to your computer and use it in GitHub Desktop.
Groovy script to execute powershell commands on Jenkins
def exec(Map map = [:], command){
def debug = map.debug ?: false
if (debug) echo "[DEBUG] powershell method called with parameter: \n $command"
def returnFileName = new Date().format("yyyyMMddHHmmssSSS")
if (debug) echo "[DEBUG] The return file name will is $returnFileName"
def pwCommand = "powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -Command \"$command\" > $returnFileName"
if(debug) echo "[DEBUG] The following command will be executed: \n $pwCommand"
bat pwCommand
if(debug) echo "[DEBUG] Reading the file $returnFileName"
def pwret = readFile "$returnFileName"
pwret = pwret.trim()
if(debug) echo "[DEBUG] Deleting the file $returnFileName"
bat "del $returnFileName"
return pwret
}
return this
@MiguelTVMS
Copy link
Author

MiguelTVMS commented May 25, 2017

Instructions

Executing

To run this script you can load the external file and call the exec method.

def powershell = load 'powershell.groovy'
powershell.exec('ls')

To debug, you can use

def powershell = load 'powershell.groovy'
powershell.exec('ls', debug: true)
To pass double quotes (") to the method you must change (") to (\")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment