Dot-Net
如何檢查文件是否被另一個程序使用 - Powershell
我正在嘗試找到一個解決方案來檢查文件是否正在被另一個程序使用。我不想閱讀文件的內容,因為在 7GB 的文件上,這可能需要一段時間。目前我正在使用下面提到的函式,這並不理想,因為腳本需要大約 5 - 10 分鐘來檢索一個值。
function checkFileStatus($filePath) { write-host (getDateTime) "[ACTION][FILECHECK] Checking if" $filePath "is locked" if(Get-Content $filePath | select -First 1) { write-host (getDateTime) "[ACTION][FILEAVAILABLE]" $filePath return $true } else { write-host (getDateTime) "[ACTION][FILELOCKED] $filePath is locked" return $false } }任何幫助將不勝感激
創建了一個解決上述問題的函式:
function checkFileStatus($filePath) { write-host (getDateTime) "[ACTION][FILECHECK] Checking if" $filePath "is locked" $fileInfo = New-Object System.IO.FileInfo $filePath try { $fileStream = $fileInfo.Open( [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read ) write-host (getDateTime) "[ACTION][FILEAVAILABLE]" $filePath return $true } catch { write-host (getDateTime) "[ACTION][FILELOCKED] $filePath is locked" return $false } }