Skip to content

Instantly share code, notes, and snippets.

@rgl
Created July 9, 2021 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgl/1861f2c6642ab79dd4cae6e488635c1a to your computer and use it in GitHub Desktop.
Save rgl/1861f2c6642ab79dd4cae6e488635c1a to your computer and use it in GitHub Desktop.
uses sysinternals handle.exe to find/list the current open handles
function Find-OpenHandle([string]$Filter = '') {
# handle.exe returns all the open files grouped by process as:
# ------------------------------------------------------------------------------
# System pid: 4 \<unable to open process>
# 720: Section \Win32kCrossSessionGlobals
# ------------------------------------------------------------------------------
# svchost.exe pid: 1208 NT AUTHORITY\SYSTEM
# 198: File (R-D) C:\Windows\System32\en-US\svchost.exe.mui
# the first line has the following fields:
# svchost.exe pid: 1208 NT AUTHORITY\SYSTEM
# ^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^
# process name | process user
# process id
# the other lines have the following fields:
# 198: File (R-D) C:\Windows\System32\en-US\svchost.exe.mui
# ^^^ ^^^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# handle type | path
# attributes
(
(
handle.exe -nobanner $Filter `
| ForEach-Object {$_.Trim()} `
| Where-Object {$_} `
| Select-Object -Skip 1
) -join "`n" -split '-{10,}\n'
) `
| ForEach-Object {
$processLine, $handlesLines = $_ -split "`n"
if ($processLine -notmatch '^(?<processName>.+?) pid: (?<processId>\d+) (?<processUser>.+)$') {
throw "unable to parse process line $processLine"
}
$processName = $Matches['processName']
$processId = $Matches['processId']
$processUser = $Matches['processUser']
@($handlesLines) | Where-Object {$_} | ForEach-Object {
if ($_ -notmatch '^(?<handle>.+?): (?<type>.+?)(\s+\((?<attributes>.+?)\))?\s+(?<path>.+)$') {
throw "unable to parse handle line $_"
}
New-Object PSObject -Property @{
ProcessName = $processName
ProcessId = $processId
ProcessUser = $processUser
Handle = $Matches['handle']
Type = $Matches['type']
Attributes = $Matches['attributes']
Path = $Matches['path']
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment