Getting GDI object count per process in Powershell

Ever wanted to query the GDI object count in PowerShell per process?

Here’s how:

"Number of GUI handles per process"
$sig = @'
[DllImport("User32.dll")]
public static extern int GetGuiResources(IntPtr hProcess, int uiFlags);
'@

Add-Type -MemberDefinition $sig -name NativeMethods -namespace Win32

$processes = [System.Diagnostics.Process]::GetProcesses()
[int]$gdiHandleCount = 0
ForEach ($p in $processes)
{
    try{
        $gdiHandles = [Win32.NativeMethods]::GetGuiResources($p.Handle, 0)
        $gdiHandleCount += $gdiHandles
        $p.Name + " : " + $gdiHandles.ToString()   
    }
    catch {
        #"Error accessing " + $p.Name
    }
}
"Total number of GDI handles " + $gdiHandleCount.ToString()

Alternatively you can use Process Explorer from Microsoft (originally sys-internals) if it is installed.

  1. Thank you, oh kind sir. This info is still helping people 4 years later!

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>