簡體   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