如何在C#中跟踪Powershell进度和错误?

时间:2016-12-19 09:45:44

标签: c# wpf powershell vmware hyper-v

我目前正在编写一个允许用户转换

的WPF应用程序
  

.vmdk(VMware vm文件)

  

.vhdx(Hyper-V vm文件)。

我正在使用一个cmdlet( ConvertTo-MvmcVirtualHardDisk ),它位于MvmcCmdlet.psd1模块中,该模块附带

  

Microsoft Virtual Machine Converter 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分钟才能完成。

任何人都可以告诉我该怎么做,跟踪进度,以便转换可以完成/完成吗?

修改

this question的区别在于我的流程无法正确完成,我想知道如何让流程完成。

1 个答案:

答案 0 :(得分:0)

Powershell的进展是一个流,就像错误,警告,调试等一样。所有流都可以通过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 streamErrorRecord个对象的集合。您可以以相同的方式收听信息,详​​细信息,警告信息,以构建所发生事件的完整日志。

另一种选择是创建一个Powershell会话的Transcript。这会将会话的所有命令和输出保存到文本文件,从您调用Start-Transcript到调用Stop-Transcript,例如:

Start-Transcript -OutputDirectory 'c:\mylogs' -noclobber -IncludeInvocationHeader

ConvertTo-MvmcVirtualHardDisk ...

Stop-Transcript

或使用C#的等效代码。

这是一种快速,简洁的方式来捕获所有问题以进行故障排除