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

如何修改PowerShell中Set-PSDebug的输出消息与格式?

修改PowerShell调试跟踪的内置提示消息

在PowerShell中,可通过以下方式启用调试跟踪:

Set-PSDebug -Trace 1
Write-Host -f DarkYellow "`nHello`n"
Set-PSDebug -Trace 0

执行上述代码会生成如下输出:

DEBUG:    1+  >>>> Write-Host -f DarkYellow "`nHello`n"

Hello

DEBUG:    1+  >>>> Set-PSDebug -Trace 0

能否将内置消息:DEBUG: 1+ >>>>修改为其他内容?


编辑:2025-06-24

显然,DEBUG:字符串位于以下两个XML资源文件中:

  • ConsoleHostUserInterfaceStrings.resx - 归属程序集:Microsoft.PowerShell.ConsoleHost
  • InternalHostUserInterfaceStrings.resx - 归属程序集:System.Management.Automation

这两个文件包含相同的XML代码:

<data name="DebugFormatString" xml:space="preserve">
    <value>DEBUG: {0}</value>
</data>

因此,理论上有两种修改方案:
(a) 重写Set-PSDebug cmdlet;
(b) 使用反射(reflection)访问内部程序集修改资源字符串。

我尝试了这两种方案,但第一种未成功,因为Set-PSDebug的输出是实时的,无法直接捕获;第二种难度较大,因为难以定位并操作对应这些XML字符串的正确程序集。

查找相关程序集类型的尝试代码

要获取*System.Management.Automation*的排序类型列表,可使用以下代码:

Add-Type -AssemblyName System.Management.Automation

[AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.FullName -like "*System.Management.Automation*" } | ForEach-Object { $_.GetTypes() | Where-Object { $_.Name -like "*" } } | Select-Object FullName | sort -Property FullName

或许筛选包含debug, format, string关键词的类型会更有价值,代码如下:

[AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.FullName -like "*System.Management.Automation*" } | ForEach-Object { $_.GetTypes() | Where-Object { $_.Name -like "*format*" -or $_.Name -like "*string*" -or $_.Name -like "*debug*" } } | Select-Object FullName | sort -Property FullName

原本期望DebuggerStrings或InternalHostUserInterfaceStrings能发挥作用,尝试访问InternalHostUserInterfaceStrings的代码如下:

# 尝试访问InternalHostUserInterfaceStrings
$T = [AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object { $_.GetType("InternalHostUserInterfaceStrings", $false) } | Where-Object { $_ -ne $null }
$T.GetFields([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static) | Select-Object Name, FieldType

$PV = $T.GetField("resourceMan", "NonPublic,Static"); "PV : $PV"; $CV = $PV.GetValue($null); "Current value: $CV"
$PV = $T.GetField("resourceCulture", "NonPublic,Static"); "PV : $PV"; $CV = $PV.GetValue($null); "Current value: $CV"

我原本希望通过SetValue()方法来修改该字符串,但尚未成功。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:27:40