如何检查另一个进程是否正在使用该文件 - Powershell

use*_*965 6 .net powershell file

我试图找到一个解决方案,它将检查另一个进程是否正在使用某个文件.我不想读取文件的内容,就像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
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

小智 8

我用来检查文件是否被锁定的函数:

function IsFileLocked([string]$filePath){
    Rename-Item $filePath $filePath -ErrorVariable errs -ErrorAction SilentlyContinue
    return ($errs.Count -ne 0)
}


use*_*965 6

创建了一个解决上述问题的函数:

 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
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

function IsFileAccessible( [String] $FullFileName )
{
  [Boolean] $IsAccessible = $false

  try
  {
    Rename-Item $FullFileName $FullFileName -ErrorVariable LockError -ErrorAction Stop
    $IsAccessible = $true
  }
  catch
  {
    $IsAccessible = $false
  }
  return $IsAccessible
}
Run Code Online (Sandbox Code Playgroud)