[英]How do I track a Powershell progress and errors in C#?
我目前正在編寫一個WPF應用程序,該應用程序允許用戶轉換
.vmdk(VMware vm文件)
到一個
.vhdx(Hyper-V vm文件)。
我正在使用一個cmdlet( ConvertTo-MvmcVirtualHardDisk ),該cmdlet駐留在MvmcCmdlet.psd1模塊隨附
Microsoft虛擬機轉換器3.0.0
我正在使用硬編碼路徑atm測試功能。
這是我當前的代碼:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Windows;
namespace PowershellTestArea
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string output { get; set; }
public MainWindow()
{
InitializeComponent();
}
private void Button_OnClick(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Runspace rs = RunspaceFactory.CreateRunspace();
rs.ThreadOptions = PSThreadOptions.UseCurrentThread;
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddCommand("Import-Module", true).AddParameter("Name", @"C:\Program Files\Microsoft Virtual Machine Converter\MvmcCmdlet.psd1");
ps.Invoke();
Debug.WriteLine(ps.HadErrors);
Thread.Sleep(3000);
ps.AddCommand("ConvertTo-MvmcVirtualHardDisk")
.AddParameter("–SourceLiteralPath", @"'C:\VM\Windows 7 x64.vmdk'")
.AddParameter("-VhdFormat", "Vhdx");
Debug.WriteLine(ps.HadErrors);
ps.BeginInvoke();
IAsyncResult asyncResult = ps.BeginInvoke<PSObject, PSObject>(null, output);
while (!asyncResult.IsCompleted)
{
Debug.WriteLine("Running...");
}
Debug.WriteLine(ps.Streams.Error.ToString());
rs.Close();
}).Start();
}
}
}
我在新線程中執行Powershell代碼的原因是該模塊已導入並且可以在運行時使用。 可以這么說,我想確保它是在同一會話中導入的。 過程:
ps.AddCommand("ConvertTo-MvmcVirtualHardDisk")
.AddParameter("–SourceLiteralPath", @"'C:\VM\Windows 7 x64.vmdk'")
.AddParameter("-VhdFormat", "Vhdx");
Debug.WriteLine(ps.HadErrors);
ps.BeginInvoke();
完成非常快(HadErrors返回false),並且在Powershell中運行時,大約需要40分鍾才能完成。
誰能告訴我該怎么做,以跟蹤進度,以便可以完成/完成轉換?
編輯:
與 該問題的 不同之處在於我的過程無法正確完成,並且我想知道如何給過程時間完成。
Powershell中的Progress是一個流,就像Error,Warning,Debug等一樣。所有流都可以通過PSDataStreams類(通過Powershell.Streams屬性公開)來使用。
您可以通過訂閱DataAdded
事件來監聽Progress流上的Progress事件,例如:
ps.Streams.Progress.DataAdded += (sender,args) => {
var records = (PSDataCollection<ProgressRecord>)sender;
var current=records[args.Index];
Console.WriteLine("VM conversion is {0} percent complete", current.PercentComplete);
};
您可以用類似的方式收聽其余的流,例如Errors流是ErrorRecord對象的集合。 您可以以相同的方式收聽信息,詳細消息,警告消息,以構造發生的事件的完整日志。
另一個選擇是創建Powershell會話的腳本 。 從您調用Start-Transcript到調用Stop-Transcript的那一刻,這會將所有命令和會話的輸出保存到文本文件,例如:
Start-Transcript -OutputDirectory 'c:\mylogs' -noclobber -IncludeInvocationHeader
ConvertTo-MvmcVirtualHardDisk ...
Stop-Transcript
或使用C#的等效代碼。
這是一種捕獲所有內容以進行故障排除的快捷方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.