繁体   English   中英

如何使用使用运行空间参数异步构造的 PowerShell object 来制作 C# 方法

[英]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();
        }

我想让这个异步。

我已经尝试过的选项:

  1. 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'.
  2. 对签名进行适当的更改以使方法异步并在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM