title: PowerShell Output Formatting from C# using DefaultDisplayPropertySet
body: <p>I am writing a PowerShell cmdlet in C#. I know one may use a formatting file to specify default output properties of a cmdlet (<a href="https://msdn.microsoft.com/en-us/library/windows/desktop/gg580944(v=vs.85).aspx" rel="nofollow">Writing a Windows PowerShell Formatting File</a>) but I recently came across a more streamlined technique (i.e. just a couple lines of code; no separate formatting file needed) to do this in a scripted cmdlet (with thanks to Kirk Munro's <a href="http://poshoholic.com/2008/07/05/essential-powershell-define-default-properties-for-custom-objects/" rel="nofollow">Define default properties for custom objects</a>, where I copied this code sample from):</p>
  
  <pre><code>$myObject = New-Object PSObject
  $myObject | Add-Member NoteProperty Name ‘My Object’
  $myObject | Add-Member NoteProperty Property1 1
  $myObject | Add-Member NoteProperty Property2 2
  $myObject | Add-Member NoteProperty Property3 3
  $myObject | Add-Member NoteProperty Property4 4
  $myObject | Add-Member NoteProperty Property5 5
  
  $defaultProperties = @('Name','Property2','Property4')
  $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultProperties)
  $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
  $myObject | Add-Member MemberSet PSStandardMembers $PSStandardMembers
  $myObject
  </code></pre>
  
  <p>The last line above displays the object, showing just the specified default properties.
  I have been searching for an equivalent way to do the same steps in my C# cmdlet but to no avail: I see no obvious access to <code>PSStandardMembers</code> on the <code>PSCmdlet</code> base class nor do I find any posts discussing the matter. Is this possible and, if so, how? </p>
  
  <hr>
  
  <p><strong>2015.03.26 Update</strong>
  With thanks to @Jaykul for pointing the way, for completeness I am attaching the actual C# code to do the task. I wrote this method to be reusable so along with the object you wish to "filter" you also pass in the property names of interest.</p>
  
  <pre><code>PSObject SetDefaultProperties(object obj, IEnumerable&lt;string&gt; defaultProperties)
  {
      var psObject = new PSObject(obj);
      psObject.Members.Add(
          new PSMemberSet("PSStandardMembers", new PSMemberInfo[]
          {
              new PSPropertySet("DefaultDisplayPropertySet", defaultProperties)
          }));
      return psObject;
  }
  </code></pre>
  
  <p>Here is how one might use it in a cmdlet--instead of sending the full result object to <code>WriteObject</code>, funnel it through the new method.</p>
  
  <pre><code>string[] DefaultProperties = {"Name", "Property2", "Property4" };
  base.WriteObject(SetDefaultProperties(myObject, DefaultProperties));
  </code></pre>