Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for locked files in Directory and find locking applicaiton

Tags:

powershell

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.

like image 808
Lima Avatar asked Jun 20 '13 02:06

Lima


People also ask

How do I find a locked file in Linux?

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.

How do you find a file that is open in another program?

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.


2 Answers

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?

like image 105
ravikanth Avatar answered Sep 30 '22 07:09

ravikanth


If you only want to check if file is locked or not use this:

try {
   [IO.File]::OpenWrite($file).close();
}catch {
   $locked = 1;
};
like image 20
Krzysztof Gapski Avatar answered Sep 30 '22 06:09

Krzysztof Gapski