簡體   English   中英

訂閱 powershell 在 c# 中的進度不起作用

[英]Subscribing to powershell progress in c# not working

I'm writing a C# GUI program that uses System.Management.Automation to execute powershell commands on an instance created at runtime, I need it to be a persistent powershell instance so I can send multiple commands and collect the output at runtime. 這按預期工作,但我在訂閱進度事件時遇到了一些問題。 它僅在我輸入錯誤命令並寫入進度已完成 -1% 時觸發。

當我輸入正確的命令時,它根本不會觸發。 錯誤和 output 事件正常工作,所以我不確定出了什么問題。

我發現另外兩個有類似的問題,但他們的解決方案對我不起作用,我將它們鏈接在下面。 到目前為止,這是我使用失敗的代碼。

 public class CodeHandler {
   public static PowerShell psInstance;

   public void init() {
     //Create powershell instance
     psInstance = PowerShell.Create();
   }

   public async Task < string > ExecutePowershellCommand(string script) {
     psInstance.AddScript(script);
     psInstance.AddCommand("Out-String");

     PSDataCollection < PSObject > outputCollection = new PSDataCollection < PSObject > ();
     outputCollection.DataAdded += outputCollection_DataAdded;

     //The Part I Can't Get To Work
     psInstance.Streams.Progress.DataAdded += (sender, eventargs) => {
       PSDataCollection < ProgressRecord > progressRecords = (PSDataCollection < ProgressRecord > ) sender;
       Console.WriteLine("!Progress is {0} percent complete", progressRecords[eventargs.Index].PercentComplete);
     };

     psInstance.Streams.Error.DataAdded += Error_DataAdded;

     IAsyncResult result = psInstance.BeginInvoke < PSObject, PSObject > (null, outputCollection);

     while (!result.IsCompleted) {
       Console.WriteLine("Waiting for pipeline to finish...");
       await Task.Delay(100);
     }

     PSInvocationState state = psInstance.InvocationStateInfo.State;
     Console.WriteLine("Execution has stopped. The pipeline state: " + state);
     if (state != PSInvocationState.Completed)
       return string.Empty;

     StringBuilder stringBuilder = new StringBuilder();
     foreach(PSObject outputItem in outputCollection) {
       stringBuilder.AppendLine(outputItem.BaseObject.ToString());
       Console.WriteLine(outputItem.BaseObject.ToString());
     }

     return stringBuilder.ToString();
   }

 }

參考:

從 C# 中獲取 Write-Progress -PercentComplete 狀態

在 C# 中讀取 Powershell 進度條 Output

添加psInstance.EndInvoke(result); 如下所示:

                       ...
 IAsyncResult result = psInstance.BeginInvoke < PSObject, PSObject > (null, outputCollection);

 while (!result.IsCompleted) {
   Console.WriteLine("Waiting for pipeline to finish...");
   await Task.Delay(100);
 }

 psInstance.EndInvoke(result);

                       ...

您的腳本需要使用Write-Progress

示例腳本

# Use Get-Command to get list of commands and store them in the $cmds variable.
$cmds = Get-Command

# Pipe the events to the ForEach-Object cmdlet.
$cmds  | ForEach-Object -Begin {
    # In the Begin block, use Clear-Host to clear the screen.
    Clear-Host

    # Set the $i counter variable to zero.
    $i = 0

    # Set the $out variable to a empty string.
    $out = ""
} -Process {
    # get name
     # Append to the out variable.
     # $out=$out + $_

     write-output ($_.Name + " " + $_.Version) 

    # Increment the $i counter variable which is used to create the progress bar.
    $i = $i+1

    # Use Write-Progress to output a progress bar.
    # The Activity and Status parameters create the first and second lines of the progress bar heading, respectively.
    Write-Progress -Activity "Searching Commands" -Status "Progress:" -PercentComplete ($i/$cmds.count*100)
} -End {
    # Display using the out variable.
    # $out
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM