【问题标题】:Default Output of a Type as Instance.ToString() in PowershellPowershell 中类型的默认输出为 Instance.ToString()
【发布时间】:2019-11-26 21:37:50
【问题描述】:

我有一个 Powershell Cmdlet,它为我返回一个 PowerShell 在表中很好地写入主机的对象。

$> 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 文件覆盖,例如与模块捆绑在一起。

【问题讨论】:

    标签: powershell formatting powershell-module


    【解决方案1】:

    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>
    

    您可以在&lt;CustomItem&gt; 中或多或少地放入您想要的内容,在这种情况下,&lt;ExpressionBinding&gt; 在正常 PowerShell 语法中使用 $_ 处理管道中的对象。您可以使用其他标签使用任意文本和间距。

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

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

    有一个更复杂的例子&lt;ExpressionBinding&gt;here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多