How can I output a PSCustomObject from a compiled Cmdlet?
17:33 17 Feb 2025

I have a compiled Cmdlet that works with Hashtables. I would like to write a [pscustomobject] of the hashtable to the pipeline. In a PowerShell script block that would be accomplished using the following cast:

[pscustomobject]$hashtable

I would like to accomplish the same from a compiled Cmdlet. The natural implementation would be

using System.Collections;
using System.Management.Automation;

[Cmdlet(VerbsData.Out,"PsCustomObject")]
public class OutPsCustomObjectCommand : PSCmdlet {
    [Parameter(Mandatory = true)]
    public Hashtable Hashtable { get; set; }
    protected override void ProcessRecord() {
        WriteObject(new PSCustomObject(Hashtable));
    }
}

however, PSCustomObject has no public constructor.

I thought new PSObject() might be equivalent, but WriteObject(new PSObject(Hashtable)) differs enough from [pscustomobject]$hashtable that they aren't even shown the same in the console:

PS\> Out-PsCustomObject -Hashtable @{ a='aye' }
Name                           Value
----                           -----
a                              aye

PS\> [pscustomobject]@{ a = 'aye' }
a
-
aye

How can I output a PSCustomObject from a compiled Cmdlet?

c# powershell powershell-cmdlet pscustomobject