我有一个Powershell Cmdlet,它返回一个对象,PowerShell在表中很好地写入主机。
$> Get-SolarLunarName -Year 1700 -Month 12
SolarDateTime Year LunarMonth LunarDay
26/12/1700 00:00:00 1700 12 16
但是,我喜欢日期时间的默认行为。
$> 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>
的例子。