1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package powershell
- import (
- "encoding/json"
- "errors"
- "fmt"
- "os/exec"
- "strings"
- )
- const commandWrapper = `$ErrorActionPreference="Stop";try { %s } catch { Write-Host $_; os.Exit(-1) }`
- func RunCommand(command string) ([]byte, error) {
- cmd := exec.Command("powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", fmt.Sprintf(commandWrapper, command))
- stdout, err := cmd.Output()
- if err != nil {
- if cmd.ProcessState.ExitCode() != 0 {
- message := strings.TrimSpace(string(stdout))
- return []byte{}, errors.New(message)
- }
- return []byte{}, err
- }
- return stdout, nil
- }
- func RunCommandf(command string, a ...interface{}) ([]byte, error) {
- return RunCommand(fmt.Sprintf(command, a...))
- }
- func RunCommandWithJsonResult(command string, v interface{}) error {
- wrappedCommand := fmt.Sprintf(commandWrapper, "ConvertTo-Json (%s)")
- wrappedCommand = fmt.Sprintf(wrappedCommand, command)
- stdout, err := RunCommandf(wrappedCommand)
- if err != nil {
- return err
- }
- err = json.Unmarshal(stdout, v)
- if err != nil {
- return err
- }
- return nil
- }
|