Skip to content

Can I use a single powershell.exe to execute multi-lines command? #173

@hanqiang2

Description

@hanqiang2

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()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions