【发布时间】:2020-12-24 06:05:31
【问题描述】:
下面是一些 C# 代码从远程连接打开运行空间,然后调用 PowerShell 的示例。
PSCollection<PSObject> Test(string remoteServerFullName, PSCredential mySuperSecretCredentials)
{
using Runspace runspace = RunspaceFactory
.CreateRunspace(new WSManConnectionInfo(new Uri($"http://{remoteServerFullName}:5985/WSMAN")) { Credential = mySuperSecretCredentials, AuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential });
runspace.Open();
using PowerShell powerShell = PowerShell.Create(runspace);
return powerShell
.AddCommand("dir")
.Invoke();
}
我想让这个异步。
我已经尝试过的选项:
- 将
runspace.Open()转换为runspace.OpenAsync()会引发异常System.Management.Automation.Runspaces.InvalidRunspaceStateException: The runspace state is not valid for this operation. ---> System.Management.Automation.Runspaces.InvalidRunspacePoolStateException: Cannot perform the operation because the runspace pool is not in the 'Opened' state. The current state is 'Opening'. - 对签名进行适当的更改以使方法异步并在
PowerShell.Create(runspace)之前放置await会导致生成错误CS1061:PowerShell does not contain a definition for GetAwaiter等。
有没有办法正确确保这里的PowerShell对象的创建等待运行空间打开后再执行?
【问题讨论】:
标签: c# powershell asynchronous async-await using