简体   繁体   English

从PowerShell cmdlet返回对象

[英]Returning an object from PowerShell cmdlet

I'm trying to create my own set of cmdlets for a PowerShell snapin. 我正在尝试为PowerShell管理单元创建自己的cmdlet集。 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. 我遇到的问题是我创建了自己的对象,我在ProcessRecord方法中创建和填充但我无法更改返回类型以允许我返回我创建的对象。

 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. 这是我的ProcessRecord方法,但是因为它覆盖了PSCmdlet中的那个,所以我无法从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? 任何人都可以帮助返回rptFileSettings对象的最佳方法,以便我可以将其与其他cmdlet中的值一起使用吗?

You don't ever need to return a value from the Cmdlet.ProcessRecord method. 您不需要从Cmdlet.ProcessRecord方法返回值。 This method has it's specific place and way of use in the PowerShell cmdlet processing lifecycle . 此方法在PowerShell cmdlet处理生命周期中具有特定的位置和使用方式。

Passing objects down the cmdlet processing pipeline is handled by the framework for you. 在cmdlet处理管道中传递对象由框架为您处理。 The same way as your cmdlet instance gets the input data it can send the data to the output for further processing. 与cmdlet实例获取输入数据的方式相同,它可以将数据发送到输出以进行进一步处理。 Passing objects to the output is done using the Cmdlet.WriteObject method inside of input processing methods, that is BeginProcessing , ProcessRecord and EndProcessing . 将对象传递给输出是使用输入处理方法内部的Cmdlet.WriteObject方法完成的,即BeginProcessingProcessRecordEndProcessing

To pass the constructed rptFileSettings object to your cmdlet output you only need to do this: 要将构造的rptFileSettings对象传递给cmdlet输出,您只需执行以下操作:

protected override void ProcessRecord()
{
    ReportFileSettings rptFileSettings = new ReportFileSettings();
    ...
    WriteObject(rptFileSettings);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM