【问题标题】:How to make a C# method using PowerShell object constructed with runspace argument asynchronous如何使用通过运行空间参数异步构造的 PowerShell 对象创建 C# 方法
【发布时间】: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();
        }

我想让这个异步。

我已经尝试过的选项:

  1. runspace.Open() 转换为runspace.OpenAsync() 会引发异常System.Management.Automation.Runspaces.InvalidRunspaceStateException: The runspace state is not valid for this operation. ---&gt; 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对象的创建等待运行空间打开后再执行?

【问题讨论】:

    标签: c# powershell asynchronous async-await using


    【解决方案1】:

    快速的方法是用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();
            });
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2020-02-16
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多