Find Locked Files with PowerShell

Image Description

Daily PowerShell #15

Scripting Daily PowerShell

October 31, 2021

There are tools available for finding open files like Process Explorer. That said, having a handy PowerShell tool is nice to search for files that are locked in Windows is great. You can use the FindOpenFile module to locate open files and files opened by a process.

Installation

The FindOpenFile module is located on the PowerShell Gallery.

Install-Module FindOpenFile

Find Files in Use

The default usage of the Find-OpenFile cmdlet will return files open in Windows along with information like the process ID that has the file open.

Find-OpenFile


ProcessId     : 10208
Handle        : 72
GrantedAccess : 1048608
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Windows\System32\DriverStore\FileRepository\FN11CD~1.INF\driver
TypeString    : File
Type          : File

ProcessId     : 10208
Handle        : 116
GrantedAccess : 1048608
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.22000.120_none_9
                d947278b86cc467
TypeString    : File
Type          : File

ProcessId     : 9232
Handle        : 72
GrantedAccess : 1048608
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Users\adamr
TypeString    : File
Type          : File

You can use the ProcessId to locate the process that has the file open.

Find-OpenFile | ForEach-Object { $_ | Add-Member -Name Process -Value (Get-Process -Id $_.ProcessId) -MemberType NoteProperty -PassThru } 

Process       : System.Diagnostics.Process (tposd)
ProcessId     : 10208
Handle        : 72
GrantedAccess : 1048608
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Windows\System32\DriverStore\FileRepository\FN11CD~1.INF\driver
TypeString    : File
Type          : File

Process       : System.Diagnostics.Process (tposd)
ProcessId     : 10208
Handle        : 116
GrantedAccess : 1048608
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.22000.120_none_9
                d947278b86cc467
TypeString    : File
Type          : File

Find Files Open by a Process

You can also search the opposite direction and find files open by a particular process.

Get-Process pwsh | Find-OpenFile 

PS C:\Users\adamr> Get-Process pwsh | Find-OpenFile

ProcessId     : 15092
Handle        : 76
GrantedAccess : 1048608
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Users\adamr
TypeString    : File
Type          : File

ProcessId     : 15092
Handle        : 868
GrantedAccess : 1048577
RawType       : 39
Flags         : 0
Name          : \Device\HarddiskVolume3\Windows\System32\en-US\winnlsres.dll.mui
TypeString    : File
Type          : File