3

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?

1 Answer 1

4

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);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

He wants to do progress stuff from inside the returned object, not from inside the cmdlet
Also, WriteProgress is on Cmdlet, not PSCmdlet.
@latkin correct, I want to access it from the method in the returned object, not from the Cmdlet itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.