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.