PowerShell - 从对象方法中写入进度

时间:2012-08-20 21:52:48

标签: c# powershell

我有一个我编写的自定义C#PowerShell Cmdlet,它输出一个对象。

[Cmdlet(VerbsCommon.Get, "CustomObj")]
public class CustomObjGet : Cmdlet
{
    protected override void ProcessRecord()
    {
        var instance = CustomObj.Get();
        WriteObject(instance);
    }
}

用法:

$output = Get-CustomObj

返回的对象有一个方法:

public class CustomObj
{
    public string Name { get; set; }

    public static CustomObj Get()
    {
        var instance = new CustomObj() { Name = "Testing" };
        return instance;
    }

    public void RestartServices () 
    {
        // Want to WriteProgress here...
    }
}

用法:

$output.RestartServices()

现在看来,该方法无法访问Cmdlet WriteProgress函数,就像在Cmdlet本身的ProcessRecord()方法中一样。

我想在该方法中执行PowerShell WriteProgress。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:4)

抱歉,误读了这个问题。这似乎适用于我的有限测试:

    public void RestartServices()
    {
        //Write
        // Want to WriteProgress here...
        for (int i = 0; i <= 100; i += 10)
        {
            Console.WriteLine("i is " + i);
            UpdateProgress(i);
            Thread.Sleep(500);
        }
    }

    private void UpdateProgress(int percentComplete)
    {
        var runspace = Runspace.DefaultRunspace;
        var pipeline = runspace.CreateNestedPipeline("Write-Progress -Act foo -status bar -percentComplete " + percentComplete, false);
        pipeline.Invoke();
    }

仅供参考,在PowerShell V3中,你也可以这样做:

    private void UpdateProgressV3(int percentComplete)
    {
        Collection<PSHost> host = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Get-Variable").AddParameter("-ValueOnly").AddArgument("Host").Invoke<PSHost>();
        PSHostUserInterface ui = host[0].UI;
        var progressRecord = new ProgressRecord(1, "REstarting services", String.Format("{0}% Complete", percentComplete));
        progressRecord.PercentComplete = percentComplete;
        ui.WriteProgress(1, progressRecord);
    }