Other posts found in this series
The SysInternals suite is a collection of tools authored by Mark Russinovich. The tools offer all kinds of deep system analysis for Windows. Some of the most commonly used tools include Process Explorer, Process Monitor and psexec. I use them all the time. After much use, I decided it would be pretty neat to try and replicate what some of the tools accomplish in PowerShell. My first target was Handle. Handle.exe returns different types of system handles that processes own. Handles can be files, directories, registry keys and all other kinds of system resources. Most frequently this is used to determine which process is locking a file. Retrieving information about systems handles currently allocated require several Win32 API calls. Using the examples found in this Stackoverflow post I was able to create an advanced function capable of returning the handles associated with processes throughout the system.
Most of the code required for this cmdlet is C# based. Due to the level of P\Invoke used, it was easier to author it this way. The first step is to grab basic information for all the handles on the system. NtQuerySystemInformation returns a collection of handle information structs. Interestingly, the struct and enumeration value are absent in the MSDN documentation for this function. Once the basic handle information is return we can begin to construct HandleInfo classes.
HandleInfo offers a couple basic properties that will be helpful once the objects are returned to the command line.
The HandleInfo class caches the Name and Type values so that it doesn’t have to look them up twice. It uses the NtQueryObject function to retrieve these values.
Once the objects have been put together in C# and Add-Type, we can create a simple advanced function to offer some better command line support. The cmdlet can filter handles by Process and handle Name. I hope to improve this further. The Sysinternals tool exposes the ability to close handles and provide a bit more information. I will also be adding the ability to filter based on handle type.
The output from the function is pretty handly . It contains the process, handle type and name.
I hope to examine a few more of the SysInternals tools and create some more interesting PowerShell solutions. Get Get-Handle here.