Tag Archives: query

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.

DirectorySearcher and filters to search AD

If you want to do a query against AD (active directory) there are several ways to do it – but (only) one proper way like usual.

The DirectorySearcher class has a ‘filter’ property that allows you to filter the returned results – oppose to you having to test each property in code. The syntax of this filter is a bit tricky (ok a lot…)

It took me a while to figure out how to properly set up a filter to do more complex queries – like when you have multiple things to filter by including ‘and’s and ‘or’s. Anyway, I found a good reference here: Search Filter Syntax.

It explains the syntax plus give some examples. It also list some special characters plus explain how to use ‘wildcards’.

Happy searching…