[英]How to make a C# method using PowerShell object constructed with runspace argument asynchronous
下面是一些 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'.
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 object 这里的创建等待运行空间打开后再执行?
快速的方法是用Task.Run
包装它:
PSCollection<PSObject> Test(string remoteServerFullName, PSCredential mySuperSecretCredentials)
{
return Task.Run(() =>
{
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();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.