9

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?

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
user1865044
  • 301
  • 3
  • 9
  • Why would you want to return anything from the `ProcessRecord` method? It has a very specific purpose and there is no use for the returned value in the [cmdlet processing lifecycle](http://msdn.microsoft.com/en-us/library/ms714429(v=vs.85).aspx). – famousgarkin Jun 24 '14 at 14:01
  • I am new to powershell and creating powershell cmdlets and so am trying to learn as I go unfortunately – user1865044 Jun 24 '14 at 14:08
  • I see. If you just want to pass the created object down the pipeline to output or another cmdlets for processing then this is done using the [`Cmdlet.WriteObject`](http://msdn.microsoft.com/en-us/library/ms568371(v=vs.85).aspx) method. In your case `WriteObject(rptFileSettings);`. – famousgarkin Jun 24 '14 at 14:10

1 Answers1

11

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);
}
famousgarkin
  • 13,687
  • 5
  • 58
  • 74