1

I have a Powershell Cmdlet, it returns an object which PowerShell writes to the host nicely in a table for me.

$> Get-SolarLunarName -Year 1700 -Month 12

SolarDateTime       Year LunarMonth LunarDay
26/12/1700 00:00:00 1700         12       16

However, I like the default behaviour for DateTime.

$> Get-Date

Tuesday, 26 November 2019 21:15:45

I really want PowerShell to write my type to the host as a string. e.g. "1700/12/16"

I understand these formats can be overridden with xml files, for example bundled with a module.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Craig.C
  • 561
  • 4
  • 17

1 Answers1

1

The documentation at MS is a little light on examples. I came up with this having trawled through a lot of unrelated examples on the web. The errors produced as I attempted to import the Module complete with an Format file were actually the most helpful in producing a valid file.

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
  <Name>ToString</Name>
  <ViewSelectedBy>
    <TypeName>My.FullyQualified.Type</TypeName>
  </ViewSelectedBy>
  <CustomControl>
    <CustomEntries>
    <CustomEntry>
      <CustomItem>
      <ExpressionBinding>
             <ScriptBlock>
              $_.tostring()
            </ScriptBlock>
      </ExpressionBinding>  
      </CustomItem>  
    </CustomEntry>
    </CustomEntries>
  </CustomControl>
</View>
</ViewDefinitions>
</Configuration>

You can put more or less what you want inside a <CustomItem>, in this case <ExpressionBinding> handles the object in the pipeline with $_ in normal PowerShell syntax. You can have arbitrary text and spacing with other tags.

I saved this file as "MyModule.Format.ps1xml" and included in the module manifest and module package:

# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @("MyModule.Format.ps1xml")

There is an example of a more complex <ExpressionBinding> here.

Craig.C
  • 561
  • 4
  • 17