Skip to content

Instantly share code, notes, and snippets.

@creatigent
Forked from MiguelTVMS/powershell.groovy
Created November 8, 2017 22:59
Show Gist options
  • Save creatigent/7b3d740ffe31aa7a73df9e0a3c72579d to your computer and use it in GitHub Desktop.
Save creatigent/7b3d740ffe31aa7a73df9e0a3c72579d 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
@kevinsyel
Copy link

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

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

How do you do this? Is the Groovy file supposed to be stored somewhere on Jenkins machine?

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