You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell变量展开时自定义ToString()脚本方法不生效问题问询

Hashtable自定义ToString()失效问题与解决方法

我尝试修改[hashtable]的ToString()函数,使其在字符串变量展开时显示自定义内容,但未达到预期效果。测试代码如下:

function customToString { 'I am Groot' }

$hash = @{ foo = 'bar' }

$hash | Add-Member -MemberType scriptmethod -Name ToString -Value $function:customToString -Force

$hash.ToString()
$hash -as [string]
"$hash"
'{0}' -f $hash

现象

仅*显式调用ToString()*时能得到自定义输出,其他隐式字符串转换场景(包括$hash -as [string]、双引号展开"$hash"、格式化字符串'{0}' -f $hash)均返回System.Collections.Hashtable。尝试用Update-TypeData更新基类,结果相同;后续尝试子类化[hashtable]重写ToString()也未成功。

补充测试(编辑1)

将$hash存入数组变量(如$array=,$hash),"$array"会使用自定义ToString(),但'{0}' -f $array和$array -as [string]仍不会触发自定义逻辑,且必须通过变量传递,直接使用"$(,$hash)"也无效。

结论与解决方法(编辑2)

这是PowerShell的已知bug,短期内不会修复。通过子类化[hashtable]可实现需求,代码如下:

class printableHashtable : hashtable {
    
    hidden static
    [printableHashtable] op_Implicit([hashtable]$hash) {
        $new = [printableHashtable]::new()
        $hash.getEnumerator() | foreach { $new.add($_.key,$_.value) }
        return $new
    }
    
    [string]ToString() { return 'I am Groot' }
}

该类可替代普通[hashtable]用于参数展开,在Write-Debug中能正常显示自定义内容,两种使用方式如下:

方式1:打印时转换

$params=@{date='2023/08/25'}
Get-Date @params
Write-Debug ([printableHashtable]$params -as [string])

方式2:直接使用该类变量

$params=[printableHashtable]@{date='2023/08/25'}
Get-Date @params
Write-Debug ($params -as [string])
Write-Debug "$params"

内容的提问来源于stack exchange,提问作者Peyre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:35:15