3

我有一个我编写的自定义 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 本身的 ProcessRecord() 方法中那样访问 Cmdlet WriteProgress 函数。

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

4

1 回答 1

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);
    }
于 2012-08-20T23:25:44.727 回答