-
Notifications
You must be signed in to change notification settings - Fork 134
Open
Description
Is there any way allow me to execute powershell commands like below? If I can execute commands in one context, then I think I can control the shell more flexible.
Currently, I check the len(stdout) to confirm if the outputs is completely wrote to buffer. But when several commands executed, the new output will be empty.
shell, err := client.CreateShell()
if err != nil {
panic(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var cmd *winrm.Command
cmd, err = shell.ExecuteWithContext(ctx, "powershell.exe")
if err != nil {
panic(err)
}
var bufOut bytes.Buffer
var bufErr bytes.Buffer
go io.Copy(&bufOut, cmd.Stdout)
go io.Copy(&bufErr, cmd.Stderr)
stdout, _ := ExecuteCommand(cmd, &bufOut, &bufErr, "hostname")
fmt.Printf(stdout)
stdout, _ = ExecuteCommand(cmd, &bufOut, &bufErr, "Get-ClusterNode | ConvertTo-Json -Compress")
fmt.Printf(stdout)
stdout, _ = ExecuteCommand(cmd, &bufOut, &bufErr, "Get-Cluster | ConvertTo-Json -Compress")
fmt.Printf(stdout)
cmd.Stdin.Close()
cmd.Wait()
cmd.Close()
shell.Close()
return
func ExecuteCommand(cmd *winrm.Command, bufOut *bytes.Buffer, bufErr *bytes.Buffer, script string) (string, string) {
stdin := bytes.NewBufferString(script + `
`)
io.Copy(cmd.Stdin, stdin)
time.sleep(xxx) // I don't know when and where I can handle a command done signal.
var newBufOut bytes.Buffer
var newBufErr bytes.Buffer
io.Copy(&newBufOut, bufOut)
io.Copy(&newBufErr, bufErr)
}
return newBufOut.String(), newBufErr.String()
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels