LockingProcessKiller.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
<#
.SYNOPSIS
  Utility to discover/kill processes that have open handles to a file or folder.
 
  Find-LockingProcess()
    Retrieves process information that has a file handle open to the specified path.
    Example: Find-LockingProcess -Path $Env:LOCALAPPDATA
    Example: Find-LockingProcess -Path $Env:LOCALAPPDATA | Get-Process
 
  Stop-LockingProcess()
    Kills all processes that have a file handle open to the specified path.
    Example: Stop-LockingProcess -Path $Home\Documents
#>




<#
.SYNOPSIS
Helper function to stop one or more processes with extra error handling and logging.
We first try stop the process nicely by calling Stop-Process().
But if the process is still running after the timeout expires then we
do a hard kill.
#>

function Kill_Process
{
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [int[]] $ProcessId,

        [parameter()]
        [int] $TimeoutSec = 2
    )

    begin
    {
        [int[]] $ProcIdS = @()
    }
    process
    {
        if ($ProcessId)
        {
            $ProcIdS += $ProcessId
        }
    }
    end
    {
        if ($ProcIdS)
        {
            [array]$CimProcS = $null
            [array]$StoppedIdS = $null
            foreach ($ProcId in $ProcIdS)
            {
                $CimProc = Get-CimInstance -Class Win32_Process -Filter "ProcessId = '$ProcId'" -Verbose:$false
                $CimProcS += $CimProc
                if ($CimProc)
                {
                    Write-Verbose "Stopping process: $($CimProc.Name)($($CimProc.ProcessId)), ParentProcessId:'$($CimProc.ParentProcessId)', Path:'$($CimProc.Path)'"
                    Stop-Process -Id $CimProc.ProcessId -Force -ErrorAction Ignore
                    $StoppedIdS += $CimProc.ProcessId
                }
                else 
                {
                    Write-Verbose "Process($ProcId) already stopped"
                }
            }

            if ($StoppedIdS)
            {
                if ($TimeoutSec)
                {
                    Write-Verbose "Waiting for processes to stop TimeoutSec: $TimeoutSec"
                    Wait-Process -Id $StoppedIdS -Timeout $TimeoutSec -ErrorAction ignore
                }

                # Verify that none of the stopped processes exist anymore
                [array] $NotStopped = $null
                foreach ($ProcessId in $StoppedIdS)
                {
                    # Hard kill the proess if the gracefull stop failed
                    $Proc = Get-Process -Id $ProcessId -ErrorAction Ignore
                    if ($Proc -and !$Proc.HasExited)
                    {
                        $ProcInfo = "Process: $($Proc.Name)($ProcessId)"
                        Write-Verbose "Killing process because of timeout waiting for it to stop, $ProcInfo" -Verbose
                        try 
                        {
                            $Proc.Kill()
                        }
                        catch 
                        {
                            Write-Warning "Kill Child-Process Exception: $($_.Exception.Message)"
                        }
                        Wait-Process -Id $ProcessId -Timeout 2 -ErrorAction ignore

                        $CimProc = Get-CimInstance -Class Win32_Process -Filter "ProcessId = '$ProcessId'" -Verbose:$false
                        if ($CimProc)
                        {
                            $NotStopped += $CimProc
                        }
                    }
                }

                if ($NotStopped)
                {
                    $ProcInfoS = ($NotStopped | ForEach-Object { "$($_.Name)($($_.ProcessId))" }) -join ", "
                    $ErrMsg = "Timeout-Error stopping processes: $ProcInfoS"
                    if (@("SilentlyContinue", "Ignore", "Continue") -notcontains $ErrorActionPreference)
                    {
                        Throw $ErrMsg
                    }
                    Write-Warning $ErrMsg
                }
                else 
                {
                    $ProcInfoS = ($CimProcS | ForEach-Object { "$($_.Name)($($_.ProcessId))" }) -join ", "
                    Write-Output "Finished stopping processes: $ProcInfoS"
                }
            }
        }
    }
}



<#
.SYNOPSIS
Retrieves process information that has a file handle open to the specified path.
We extract the output from the handle.exe utility from SysInternals:
Link: https://docs.microsoft.com/en-us/sysinternals/downloads/handle
 
.Example
Find-LockingProcess -Path $Env:LOCALAPPDATA
 
.Example
 Find-LockingProcess -Path $Env:LOCALAPPDATA | Get-Process
#>

function Find-LockingProcess
{
    [OutputType([array])]
    [CmdletBinding()]
    param (
        [Parameter(Position = 0)]
        [object] $Path
    )

    $AppInfo = Get-Command $Script:HandleApp -ErrorAction Stop
    if ($AppInfo)
    {
        #Initialize-SystemInternalsApp -AppRegName "Handle"
        $PathName = (Resolve-Path -Path $Path).Path.TrimEnd("\") # Ensures proper .. expansion & slashe \/ type
        $LineS = & $AppInfo.Path -accepteula -u $PathName -nobanner
        foreach ($Line in $LineS) 
        {
            # "pwsh.exe pid: 5808 type: File Domain\UserName 48: D:\MySuff\Modules"
            if ($Line -match "(?<proc>.+)\s+pid: (?<pid>\d+)\s+type: (?<type>\w+)\s+(?<user>.+)\s+(?<hnum>\w+)\:\s+(?<path>.*)\s*")
            {
                $Proc = $Matches.proc.Trim()
                if (@("handle.exe", "Handle64.exe") -notcontains $Proc)
                {
                    $Retval = [PSCustomObject]@{
                        Process = $Proc
                        Pid     = $Matches.pid
                        User    = $Matches.user.Trim()
                        #Handle = $Matches.hnum
                        Path    = $Matches.path
                    }
                    Write-Output $Retval
                }
            }
        }
    }
}



<#
.SYNOPSIS
Kills all processes that have a file handle open to the specified path.
 
.Example
Stop-LockingProcess -Path $Home\Documents
#>

function Stop-LockingProcess
{
    [CmdletBinding()]
    param (
        [Parameter(Position = 0)]
        [object] $Path
    )

    $ProcS = Find-LockingProcess -Path $Path | Sort-Object -Property Pid -Unique
    Kill_Process -ProcessId $ProcS.Pid
}



######### Initialize Module #########
function DownloadHandleApp($Path)
{
    $ZipFile = "Handle.zip"
    $ZipFilePath = "$Path\$ZipFile"
    $Uri = "https://download.sysinternals.com/files/$ZipFile"
    try 
    {
        Remove-Item -Path $Path -Recurse -Force -ErrorAction SilentlyContinue
        $null = New-Item -ItemType Directory -Path $Path -Force -ErrorAction Stop
        Invoke-RestMethod -Method Get -Uri $Uri -OutFile $ZipFilePath -ErrorAction Stop
        Expand-Archive -Path $ZipFilePath -DestinationPath $Path -Force -ErrorAction Stop
        Remove-Item -Path $ZipFilePath -ErrorAction SilentlyContinue
    }
    catch 
    {
        Remove-Item -Path $Path -Recurse -Force -ErrorAction SilentlyContinue
        Throw "Failed to download dependency: handle.exe from: $Uri"
    }
}

$Script:HandleDir = "$PSScriptRoot\handle"
$Script:HandleApp = "$HandleDir\handle.exe"
if (!(Test-Path -Path $Script:HandleApp))
{
    DownloadHandleApp -Path $HandleDir
}