我正在尝试为PowerShell管理单元创建自己的cmdlet集。我遇到的问题是我创建了自己的对象,该对象在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;
 }

这是我的ProcessRecord方法,但是由于它覆盖了PSCmdlet的方法,因此我无法从void更改返回类型。

谁能提供最好的方法来返回 rptFileSettings 对象,以便我可以将其与其他cmdlet中的值一起使用?

最佳答案

您不需要从 Cmdlet.ProcessRecord 方法返回值。该方法在PowerShell cmdlet processing lifecycle中具有特定的位置和使用方式。

框架将为您处理将对象向下传递到cmdlet处理管道的过程。与cmdlet实例获取输入数据的方式相同,它可以将数据发送到输出以进行进一步处理。使用输入处理方法中的 Cmdlet.WriteObject 方法将对象传递到输出,即BeginProcessingProcessRecordEndProcessing

要将构造的rptFileSettings对象传递到您的cmdlet输出,只需执行以下操作:

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

关于c# - 从PowerShell cmdlet返回对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24388357/

10-09 17:38
查看更多