I am wanting to create a PowerShell script that will find any files that are locked within a supplied directory and return the application/process that has locked the file.
I have found a script which goes through a directory and when it finds a locked file will stop and report the file is locked.
Function Test-Lock{
param(
[parameter(ValueFromPipeline=$true)]
$Path
)
Process {
if($Path.Attributes -ne 'Directory'){
$oFile = New-Object System.IO.FileInfo $Path.FullName
$locked=$false
try{
$oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
$oStream.Close()
}
catch{
write-host $Error[0]
$locked=$true
New-Object PSObject -Property @{'Path'=$Path.FullName;'Locked?'=$locked} | Select Path,Locked?
}
}
}
}
$lockedfiles=(gci C:\temp | Test-Lock)
$lockedfiles | Format-Table -auto
This returns:
Path Locked?
---- -------
C:\temp\ReportReq.doc True
I cannot work out how to find the application or proecess that has this file locked.
Finding the locked files In order to view all locked files on the current system, simply execute lslk(8) . In this document as an example, we will find and remove a locked file from a KDE session on a shared storage, where multiple clients are mounting their home partitions from an NFS server.
Simply open the Process Explorer Search via Find > Find Handle or DLL (or press Ctrl + Shift + F), enter the file name, and wait for the list of processes accessing your file. You can't close the process from the search window, but you can use Process Explorer or Windows Task Manager to close the offending application.
Well, You need to use handle.exe from sysinternals to achieve this. Adam Driscoll, a PowerShell MVP, wrote a PowerShell version of sysinternals handle.exe. You can check that at: https://github.com/adamdriscoll/PoshInternals/blob/master/Handle.ps1
Also, there is a similar question answered here by Keith Hill: PowerShell script to check an application that's locking a file?
If you only want to check if file is locked or not use this:
try {
[IO.File]::OpenWrite($file).close();
}catch {
$locked = 1;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With