src/Get-PsDump.ps1
#requires -version 6 using namespace System.IO using namespace System.Text using namespace Microsoft.Win32.SafeHandles Set-Alias -Name psdump -Value Get-PsDump function Get-PsDump { [CmdletBinding()] param( [Parameter(Mandatory, Position=0)] [ValidateScript({!!($script:ps = Get-Process -Id $_ -ErrorAction 0)})] [Int32]$Id, [Parameter()] [ValidateNotNullOrEmpty()] [ValidateSet('MiniDump', 'FullDump')] [String]$DumpType = 'MiniDump', [Parameter()] [ValidateNotNullOrEmpty()] [ValidateScript({Test-Path $_})] [String]$SavePath = $pwd.Path ) begin { $kernel32, $dmp = (New-Delegate kernel32 -Signature @{ LoadLibraryW = [Func[[Byte[]], IntPtr]] FreeLibrary = [Func[IntPtr, Boolean]] }), "${SavePath}\$($ps.Name)_${Id}.dmp" } process {} end { try { if (!($dll = $kernel32.LoadLibraryW.Invoke( [Encoding]::Unicode.GetBytes('dbghelp.dll') ))) { throw [DllNotFoundException]::new() } $dbghelp, $fs, $numeric = (New-Delegate dbghelp -Signature @{ MiniDumpWriteDump = [Func[IntPtr, UInt32, SafeFileHandle, UInt32, IntPtr, IntPtr, IntPtr, Boolean]] }), [File]::Create($dmp), (6, 261)[$DumpType -eq 'MiniDump'] if (!$dbghelp.MiniDumpWriteDump.Invoke( $ps.Handle, ${Id}, $fs.SafeFileHandle, $numeric, [IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero )) { $err = $true throw [InvalidOperationException]::new() } } catch { Write-Verbose $_ } finally { if ($fs) { $fs.Dispose() } if ($dll) { if (!$kernel32.FreeLibrary.Invoke($dll)) { Write-Verbose 'Could not release dbghelp.dll library.' } } if ($err) { Remove-Item $dmp -Force -ErrorAction 0 } } $ps.Dispose() } } |