PowerShell自定义List子类:实现自动字符串转换与自定义默认显示
PowerShell继承List的自定义类:字符串转换与默认显示解决方案
1. 修复字符串自动转换(实现\连接而非空格分隔)
继承System.Collections.Generic.List[Object]后,PowerShell默认会将集合元素用空格拼接成字符串。要覆盖这个行为,需结合重写ToString()和自定义类型转换器:
代码实现
# 定义元素类 class MyItemClass { [string]$Type [string]$Name [string]$Value MyItemClass([string]$Type, [string]$Name, [string]$Value) { $this.Type = $Type $this.Name = $Name $this.Value = $Value } } # 自定义类型转换器,控制字符串转换逻辑 class MyPathConverter : System.Management.Automation.PSTypeConverter { [bool] CanConvertTo([object]$sourceValue, [type]$destinationType) { return $destinationType -eq [string] } [object] ConvertTo([object]$sourceValue, [type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase) { # 提取元素的Name属性(或直接转字符串),用\连接 $items = $sourceValue | ForEach-Object { if ($_ -is [MyItemClass]) { $_.Name } else { "$_" } } return $items -join '\' } # 实现其他必要接口方法(返回默认值即可) [bool] CanConvertFrom([object]$sourceValue, [type]$destinationType) { return $false } [object] ConvertFrom([object]$sourceValue, [type]$destinationType, [IFormatProvider]$formatProvider, [bool]$ignoreCase) { return $null } } # 标记类型转换器,同时重写ToString()确保直接调用生效 [TypeConverter([MyPathConverter])] class MyPathClass : System.Collections.Generic.List[Object] { [string] ToString() { $items = $this | ForEach-Object { if ($_ -is [MyItemClass]) { $_.Name } else { "$_" } } return $items -join '\' } }
效果验证
- 字符串插值:
"$MyPath"会自动返回\连接的结果(如添加MyItemClass实例后得到b\e\h) - 强制类型转换:
[string]$MyPath也会返回预期格式
2. 自定义默认显示效果(展示元素完整属性)
直接输出$MyPath时,PowerShell默认会逐行枚举List元素。要展示每个元素的Type/Name/Value完整属性,需自定义PowerShell的类型格式:
步骤1:创建格式文件(MyPathFormat.ps1xml)
<?xml version="1.0" encoding="utf-8"?> <Configuration> <ViewDefinitions> <View> <Name>MyPathClass</Name> <ViewSelectedBy> <TypeName>MyPathClass</TypeName> </ViewSelectedBy> <ListControl> <ListEntries> <ListEntry> <ListItems> <ListItem> <PropertyName>Count</PropertyName> <Label>元素总数</Label> </ListItem> <ListItem> <ScriptBlock> # 格式化每个元素的完整属性 $this | ForEach-Object { [PSCustomObject]@{ Type = if ($_ -is [MyItemClass]) { $_.Type } else { '字符串' } Name = if ($_ -is [MyItemClass]) { $_.Name } else { "$_" } Value = if ($_ -is [MyItemClass]) { $_.Value } else { $null } } } | Format-Table -AutoSize | Out-String -Stream </ScriptBlock> </ListItem> </ListItems> </ListEntry> </ListEntries> </ListControl> </View> </ViewDefinitions> </Configuration>
步骤2:加载格式文件
Update-FormatData -PrependPath .\MyPathFormat.ps1xml
效果验证
直接输出$MyPath时,会显示元素总数,以及每个元素的完整属性列表,而非默认的逐行元素。
补充方案(无需格式文件)
如果不想全局注册格式,可在类中添加自定义显示方法,手动调用:
class MyPathClass : System.Collections.Generic.List[Object] { # ... 原有代码 ... [void] Show() { $this | ForEach-Object { [PSCustomObject]@{ Type = if ($_ -is [MyItemClass]) { $_.Type } else { '字符串' } Name = if ($_ -is [MyItemClass]) { $_.Name } else { "$_" } Value = if ($_ -is [MyItemClass]) { $_.Value } else { $null } } } | Format-Table -AutoSize } }
调用方式:$MyPath.Show()
内容的提问来源于stack exchange,提问作者iRon
相关产品推荐
相关产品推荐

