github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/utils/exec/exec_windows.go (about) 1 package exec 2 3 import ( 4 "os/exec" 5 "bytes" 6 "syscall" 7 ) 8 9 var CheckError = ";if($? -eq $false){ exit 11 };" 10 11 12 func RunPSCommand(script string) (string, error){ 13 cmd := []string{ 14 "powershell", 15 "-Command", 16 `"`, 17 `$ErrorActionPreference = 'Stop';`, 18 script, 19 `"`, 20 } 21 return RunCommand(cmd) 22 } 23 24 func RunCommand(args []string) (string, error) { 25 out, err := exec.Command(args[0], args[1:]...).CombinedOutput() 26 if err != nil { 27 return string(out), err 28 } 29 return string(out), nil 30 } 31 32 func RunCommands(run RunParams) (*ExecResponse, error) { 33 ps := exec.Command("powershell.exe", "-noprofile", "-noninteractive", "-command", "$input|iex") 34 if run.Environment != nil { 35 ps.Env = run.Environment 36 } 37 if run.WorkingDir != "" { 38 ps.Dir = run.WorkingDir 39 } 40 ps.Stdin = bytes.NewBufferString(run.Commands) 41 42 stdout := &bytes.Buffer{} 43 stderr := &bytes.Buffer{} 44 45 ps.Stdout = stdout 46 ps.Stderr = stderr 47 48 err := ps.Start() 49 if err == nil { 50 err = ps.Wait() 51 } 52 result := &ExecResponse{ 53 Stdout: stdout.Bytes(), 54 Stderr: stderr.Bytes(), 55 } 56 if ee, ok := err.(*exec.ExitError); ok && err != nil { 57 status := ee.ProcessState.Sys().(syscall.WaitStatus) 58 if status.Exited() { 59 // A non-zero return code isn't considered an error here. 60 result.Code = status.ExitStatus() 61 err = nil 62 } 63 logger.Infof("run result: %v", ee) 64 } 65 return result, err 66 }