How do I run a PowerShell command from groovy the same way as "cmd /c <command>".execute()?
I used a Groovy class to execute a PowerShell script. This is a little more elaborate than just executing a command, but I thought it might be helpful.
import groovy.util.logging.Log4jimport org.springframework.stereotype.Component@Component@Log4jclass PowerShellUtil { def exec(debug, command, args){ def powerShellCommand = ".\\${command} ${args}" def shellCommand = "powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -Command \"${powerShellCommand}\"" if (debug) log.debug powerShellCommand def process = shellCommand.execute() def out = new StringBuffer() def err = new StringBuffer() process.consumeProcessOutput(out, err) process.waitFor() if(out.size() > 0 && debug) log.debug out if(err.size() > 0) log.error err }}
Then I can execute the script with:
PowerShellUtil psUtil = new PowerShellUtil()psUtil.exec(true, 'script.ps1','script-args')