如何使用 PowerShell Core 写入调试流以便它被 SysInternals 捕获 DBGVIEW.EXE

How to write to debug stream with PowerShell Core so it's captured by SysInternals DBGVIEW.EXE

我有很多脚本使用 OutputDebugString Windows API 来输出有意义的状态信息,这样当它们 运行 在生产中时,我可以拉打开 SysInternals 调试查看器,看看发生了什么。

当 PowerShell Core 7 发布时,我想将我的脚本移过来,这样我就可以利用新功能。我希望只要我在 Windows 上 运行 Pwsh.exe,这个 Windows 特定的代码就可以工作,但我错了。

Write-Debug 一点帮助也没有。

是否有跨平台支持的方式来输出消息,在 Windows 上,Debug Viewer 可以读取这些消息?

FWIW,这是我使用了很长时间的代码:

$VB = @"
'http://www.pinvoke.net/default.asp
Public Class WinAPI
    <System.Runtime.InteropServices.DllImport("kernel32.dll")> _
    Public Shared Sub OutputDebugString(ByVal lpOutputString As String)
    End Sub
End Class
"@

Add-Type $VB -Language Visualbasic

function Write-DebugMessage([string]$Message)
{
    $Msg = "[$Script:ScriptHelperAppName] $Message"
    [WinAPI]::OutputDebugString($Msg)
    Write-Verbose $Msg
}

好吧,这太简单了。我从没想过 pwsh.exe 可以编译一种 .Net 语言,但不能编译另一种。

我刚刚将 .Net 代码转换为 C#,它工作正常。

$WinAPI = @"
    public class WinAPI
    {
    [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    public static extern void OutputDebugString(string message);
    }
"@

Add-Type $WinAPI -Language CSharp

[WinAPI]::OutputDebugString("C# Test")

内置方式:

[System.Diagnostics.Debug]::WriteLine('hello')