Powershell 中类型的默认输出为 Instance.ToString()

Default Output of a Type as Instance.ToString() in Powershell

我有一个 Powershell Cmdlet,它 returns 一个对象,PowerShell 为我在 table 中很好地写入主机。

$> Get-SolarLunarName -Year 1700 -Month 12

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

不过,我喜欢 DateTime 的默认行为。

$> Get-Date

Tuesday, 26 November 2019 21:15:45

我真的希望 PowerShell 将我的类型作为字符串写入主机。例如“1700/12/16”

我知道这些格式可以被 xml 文件覆盖,例如与模块捆绑在一起。

MS 上的文档对示例略有说明。我在网上浏览了很多不相关的例子后想到了这个。当我尝试导入带有格式文件的模块时产生的错误实际上对生成有效文件最有帮助。

<?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>

您可以或多或少地在 <CustomItem> 中放置您想要的内容,在这种情况下,<ExpressionBinding> 在普通 PowerShell 语法中使用 $_ 处理管道中的对象。您可以使用任意文本和与其他标签的间距。

我将此文件保存为 "MyModule.Format.ps1xml" 并包含在模块清单和模块包中:

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

有一个更复杂的例子<ExpressionBinding> here