我想从C#在远程计算机上执行powershell命令。我使用
实现了同样的目标 public Collection<PSObject> RunScript(String Command)
{
Collection<PSObject> results = null;
using (var powershell = PowerShell.Create())
{
Runspace runspace = RunspaceFactory.CreateRunspace(connection);
runspace.Open();
powershell.Runspace = runspace();
powershell.AddScript(Command);
results = powershell.Invoke();
runspace.Close();
}
return results;
}
}
我能够第一次执行此操作。但是当我第二次尝试执行这个函数时,它给了我错误,运行空间被关闭。实际上我最后关闭了它,但为什么在调用函数时它不会重新打开。
答案 0 :(得分:1)
你关闭了它,但你没有丢弃它:
using (var powershell = PowerShell.Create())
using (Runspace runspace = RunspaceFactory.CreateRunspace(connection))
{
runspace.Open();
powershell.Runspace = runspace();
powershell.AddScript(Command);
results = powershell.Invoke();
runspace.Close();
}