Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function Get-LockingProcesses()
- {
- [cmdletbinding()]
- Param(
- [Parameter(Position=0,Mandatory=$True,
- HelpMessage="What is the path or filename? You can enter a partial name without wildcards")]
- [Alias("name")]
- [ValidateNotNullorEmpty()]
- [string]$Path
- )
- #define the path to Handle.exe, uses the PSScriptRoot variable to get the current path of the executing code
- $handleUtilityFilePath = "$PSScriptRoot\handle.exe"
- #Ensure the file is present
- If (Test-Path -Path $handleUtilityFilePath -PathType Leaf)
- {
- #Arguments to handle specifying to accept license and search for usernames
- $data = &$handleUtilityFilePath /accepteula $path -u
- #Define regex including capture groups for each column we are interested in, throw away the code before the path
- [string]$matchPattern = '^(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\b(\d+)\b)\s+type:\s+(?<Type>\w+)\s+(?<Username>\S+)\s+\w+:\s+(?<Path>\S+)$'
- $lockingProcesses = @()
- #Iterate ove the lines in the output of handle and try to match each one usign the reg ex
- foreach ($line in $data)
- {
- $myMatch = [RegEx]::Match($line, $matchPattern)
- if ($myMatch.Value)
- {
- #Match found so add a cusom object using the capture groups to our array
- $lockingProcesses += [PSCustomObject] @{
- FullName = $myMatch.groups["Name"].value
- Name = $myMatch.groups["Name"].value.split(".")[0]
- ID = $myMatch.groups["PID"].value
- Type = $myMatch.groups["Type"].value
- Username = $myMatch.groups["Username"].value
- Path = $myMatch.groups["Path"].value
- CommandLine = (Get-WmiObject Win32_Process -Filter "ProcessId = $($myMatch.groups["PID"].value)").CommandLine #Include the command line of the process incase of multiple entries or generic process names
- }
- }
- }
- if ($lockingProcesses.Count -eq 0)
- {
- Write-Warning "No matching handles found"
- }
- #Remove duplicate entries
- $lockingProcesses = $lockingProcesses | Select-Object -Unique
- return ,[array]$lockingProcesses #unravel when sending pack to ensure it is kept as an array
- }
- else
- {
- Throw "Cannot find required utility ""handle.exe"" at path ""$handleUtilityFilePath"""
- }
- } #end function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement