John Chapman
John Chapman

Reputation: 898

PowerShell - Write Progress from within Object Method

I have a custom C# PowerShell Cmdlet that I have written that outputs an object.

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

Usage:

$output = Get-CustomObj

The object returned has a method:

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...
    }
}

Usage:

$output.RestartServices()

As it stands now, that method doesn't have access to the Cmdlet WriteProgress function like you would in the ProcessRecord() method of the Cmdlet itself.

I'd like to do a PowerShell WriteProgress from within that method. Any ideas on how I can do that?

Upvotes: 3

Views: 1867

Answers (1)

Keith Hill
Keith Hill

Reputation: 201652

Sorry, misread the question. This seems to work in my limited testing:

    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();
    }

FYI, in PowerShell V3, you can also do it this way:

    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);
    }

Upvotes: 4

Related Questions