[英]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.