'How to write to debug stream with PowerShell Core so it's captured by SysInternals DBGVIEW.EXE
I have scores of scripts that use the OutputDebugString
Windows API to output meaningful state information so that when they're running in Production, I can pull up the SysInternals debug viewer and see what all is happening.
When PowerShell Core 7 comes out, I'd like to move my scripts over, so I can take advantage of new features. I expected that this Windows-specific code would work as long as I am running Pwsh.exe on Windows, but I was wrong.
Write-Debug doesn't help at all.
Is there a cross-platform supported way to output messages that, on Windows, can be read by Debug Viewer?
FWIW, here's the code I've been using for a very long time:
$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
}
Solution 1:[1]
OK, so this was embarrassingly simple. It never occurred to me that pwsh.exe would be able to compile one .Net language but not another.
I just converted the .Net code to C# and it works fine.
$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")
Solution 2:[2]
A builtin way:
[System.Diagnostics.Debug]::WriteLine('hello')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kevin Buchan |
Solution 2 | Dess |