如何在 PowerShell 中定义我的类对象的字符串表示形式?

问题描述 投票:0回答:1

我正在尝试用 C# 制作一些 PowerShell cmdlet,并创建一个 DataChunk 类来存储二进制数据。它只是保存 byte[] 数组。目标是将文件中的字节读取到 DataChunk 以显示我如何需要它。所以我写了ToString()方法。但 PowerShell 似乎没有使用它。为什么?

PS> $data = Read-BinaryData test.bin
PS> $data.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    DataChunk                                System.Object

这就是我需要的:

PS> $data.ToString()
07 65 20 AE F6 8D 4F 00 97 A8 33 C9 81 EB 80 AE 92 87 7D 08

这就是现在的运作方式:

PS> $data

Count
-----
   20

课程很简单:

public class DataChunk
{
    byte[] data;
    public int Count => data.Length;
    public override string ToString() { ... }
}

如何让我自己的类像我需要的那样显示在 PowerShell 中?

c# powershell
1个回答
0
投票

您可以为您的类型定义自己的格式数据,请参阅

about Format.ps1xml
。在这种情况下,您可以将
CustomControl
ExpressionBinding
标签一起使用。

首先您需要定义

ps1xml
并将其存储在文件中,在本例中,文件保存在当前位置,名称为
DataChunk.format.ps1xml
:

Set-Content DataChunk.Format.ps1xml -Value @'
<Configuration>
  <ViewDefinitions>
    <View>
      <Name>MyCustomTestView</Name>
      <ViewSelectedBy>
        <TypeName>DataChunk</TypeName>
      </ViewSelectedBy>
      <CustomControl>
        <CustomEntries>
          <CustomEntry>
            <CustomItem>
              <ExpressionBinding>
                <ScriptBlock>
                  $_.ToString()
                </ScriptBlock>
              </ExpressionBinding>
            </CustomItem>
          </CustomEntry>
        </CustomEntries>
      </CustomControl>
    </View>
  </ViewDefinitions>
</Configuration>
'@

然后您需要使用此文件更新自定义类型的格式数据:

Update-FormatData -PrependPath .\DataChunk.format.ps1xml

最后你可以测试一下:

Add-Type @'
using System;

public class DataChunk
{
    private readonly byte[] _data;
    public int Count => _data.Length;
    public DataChunk(byte[] bytes) => _data = bytes;
    public override string ToString() => BitConverter.ToString(_data).Replace('-',' ');
}
'@

$bytes = 7, 101, 32, 174, 246, 141
[DataChunk]::new($bytes)

# Should output:
#
# 07 65 20 AE F6 8D

这里值得注意的是,如果您正在开发二进制模块,则无需手动更新格式数据,您可以将

format.ps1xml
文件的路径添加到 .psd1
 元素中的 
模块清单 (
FormatsToProcess
) 中。

© www.soinside.com 2019 - 2024. All rights reserved.