Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an object from PowerShell cmdlet

I'm trying to create my own set of cmdlets for a PowerShell snapin. The problem I'm having is that I've created my own object that I create and populate within the ProcessRecord method but I'm not able to change the return type to allow me to return the object that I created.

 protected override void ProcessRecord()
 {
    ReportFileSettings rptFileSettings = new ReportFileSettings();
    rptFileSettings.Enabled = string.Equals((reader.GetAttribute("Enabled").ToString().ToLower()), "yes");
    rptFileSettings.FileLocation = reader.GetAttribute("FileLocation").ToString();
    rptFileSettings.OverwriteExisting = string.Equals(reader.GetAttribute("OverwriteExistingFile").ToString().ToLower(), "yes");
    rptFileSettings.NoOfDaysToKeep = int.Parse(reader.GetAttribute("NumberOfDaysToKeep").ToString());
    rptFileSettings.ArchiveFileLocation = reader.GetAttribute("ArchiveFileLocation").ToString();

    return rptFileSettings;
 }

This is my ProcessRecord method but as it's overriding the one from PSCmdlet I cannot change the return type from void.

Can anyone help with the best way to return the rptFileSettings object so as I can then use it with its values in other cmdlets?

like image 624
user1865044 Avatar asked Jun 24 '14 13:06

user1865044


1 Answers

You don't ever need to return a value from the Cmdlet.ProcessRecord method. This method has it's specific place and way of use in the PowerShell cmdlet processing lifecycle.

Passing objects down the cmdlet processing pipeline is handled by the framework for you. The same way as your cmdlet instance gets the input data it can send the data to the output for further processing. Passing objects to the output is done using the Cmdlet.WriteObject method inside of input processing methods, that is BeginProcessing, ProcessRecord and EndProcessing.

To pass the constructed rptFileSettings object to your cmdlet output you only need to do this:

protected override void ProcessRecord()
{
    ReportFileSettings rptFileSettings = new ReportFileSettings();
    ...
    WriteObject(rptFileSettings);
}
like image 199
famousgarkin Avatar answered Sep 18 '22 15:09

famousgarkin