问题描述
我正在尝试通过用 Go 编写的应用程序远程使用 Powershell,但无法存储在调用 New-PSSession 命令时返回的会话变量。
package main
import (
"bytes"
"fmt"
"os/exec"
)
type PowerShell struct {
powerShell string
}
func New() *PowerShell {
ps,_ := exec.LookPath("powershell.exe")
return &PowerShell{
powerShell: ps,}
}
func (p *PowerShell) Execute(args ...string) (stdOut string,stdErr string,err error) {
cmd := exec.Command(p.powerShell,args...)
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
stdOut,stdErr = stdout.String(),stderr.String()
return
}
func main() {
posh := New()
stdout,stderr,err := posh.Execute("$session = New-PSSession -ComputerName url.test.com")
fmt.Println(stdout)
fmt.Println(stderr)
if err != nil {
fmt.Println(err)
}
stdout,err = posh.Execute("Invoke-Command -Session $session -Scriptblock {New-Item -type file d:\\golang_test_api\\blah.txt}")
fmt.Println(stdout)
fmt.Println(stderr)
if err != nil {
fmt.Println(err)
}
}
虽然通过分号链接这些命令有效,但我需要一个解决方案来增加 $session 变量的范围。 我收到此错误,供参考:
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty,and then try the command again.
At line:1 char:25
+ Invoke-Command -Session $session -Scriptblock {New-Item -type file d: ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command],ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterargumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)