How can I force a Powershell script to wait overwriting a file until another process is finished reading it?

守給你的承諾、 提交于 2019-12-06 07:56:35

In some cases, you may not be able to overwrite it if the file is open.

Otherwise, you will have to devise some other mechanism to signal that the reader has finished reading it. This is not really related to powershell. For example, the reader can create a "lock file" to notify the writer that the file is being read, which it deletes after completing the read. The powershell script can delete the file if the lock file does not exist.

I use this function to test if file il locked, but in file txt opened by notepad for example the file isn't locked:

function Test-FileLock {

  param (
        [parameter(Mandatory=$true)]
        [string]$Path
    )

  $oFile = New-Object System.IO.FileInfo $Path    
  if ((Test-Path -Path $Path) -eq $false)
  {
    $false
    return
  }      
  try
  {
      $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
      if ($oStream)
      {
        $oStream.Close()
      }
      $false
  }
  catch
  {
    # file is locked by a process.
    $true
  }
}

You can use the static Open method in the System.IO.File class. If you try open a file and it is being used by another process it will throw an exception, if you wrap it in a try/catch block, you will be able to tell if an exception has been thrown and therefore return $true in the catch block which will mean its in use.

function Get-FileStatus([string]$Path)
{
     try
     {
        [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
        return $false
     }
     catch
     {
        return $true
     }
}



if((Get-FileStatus -Path "C:\myfile.bin"))
{
   Write-Host "File in Use"
}
else
{
   Write-Host "File Not in Use"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!