Reputation: 5832
I am writing a script that copies over log files and I want to make certain that the log file is not being written to before I copy it.
I created a function that is supposed to check for this case by trying to open the file. The assumption is that if another application has the file open, the function would detect this condition in the $oFile.Open call.
I tested this function by opening the test file in Notepad and then ran the function and it did not report any issues. In other words $oFile.Open returned true even though the file was already open in NotePad.
Can someone help me understand what's going on here?
Thanks
function isFileLocked([string]$Path) {
$oFile = New-Object System.IO.FileInfo $Path
### Make sure the path is good
if ((Test-Path -Path $Path) -eq $false)
{
echo "Bad Path"
return $false
}
#Try opening file
$oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
if ($oStream)
{
echo "Got valid stream so file must not be locked"
$oStream.Close()
return $false
} else {
echo "InValid stream so file is locked"
return $true
}
}
$file="C:\Users\Tom\Daily_Reviews_0001-1191.journal"
$result = isFileLocked($file)
echo $result
Upvotes: 0
Views: 5192
Reputation: 5241
Not all programs hold on to the file handles. Notepad opens the file, reads its contents and then closes it. So there is no way of knowing what programs may have a file open, but that also means you shouldn't need to know if a file is open, only if there is handle in use, which your code does.
Upvotes: 2