10

I am trying to find a solution which will check whether a file is being used by another process. I don't want to read the contents of the file, as on a 7GB document, this could take a while. Currently I am using the function mentioned below, which is not ideal as the script takes about 5 - 10 minutes to retrieve a value.

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
    }
}

Any help would be greatly appreciated

6 Answers 6

12

Created a function which solves the above problem:

 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
        }
    }
5
  • Thank you very much for your code. It is very useful. I am using it to test if a file on a shared network location is available for use. Every a few days they upload a new big file to that location (which takes a few hours to upload) and I want to make sure that the uploading is finished so that I can safely copy and download that file to my local machine. Do you see any flaw in my concept?
    – FrozenLand
    Oct 16, 2013 at 18:00
  • Is there a reason that this doesn't call $fileStream.Dispose() before exiting?
    – sam-6174
    Jan 25, 2016 at 14:40
  • @user2426679 I've read that garbage collector will take care of it, unless you are creating too many objects within a certain timeframe
    – tonysepia
    Jun 21, 2017 at 7:39
  • This actually doesn't work as written for me, needed to replace $fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read) with $fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Write, [System.IO.FileShare]::Read) to trigger an error when the file was being used by another process.
    – mlibby
    Jan 16, 2020 at 16:35
  • all the solutions here are returning false positive for me. like the file is always locked
    – Ori Wiesel
    Sep 30, 2020 at 10:32
8

The function i use to check whether a file is locked or not :

function IsFileLocked([string]$filePath){
    Rename-Item $filePath $filePath -ErrorVariable errs -ErrorAction SilentlyContinue
    return ($errs.Count -ne 0)
}
1
  • For my case this didn't work. I want to copy over an existing file, so I ran this check on it and got no errors, but when it got to the copy step, there was an error that the file was being used by another process.
    – mlibby
    Jan 16, 2020 at 16:25
5
function IsFileAccessible( [String] $FullFileName )
{
  [Boolean] $IsAccessible = $false

  try
  {
    Rename-Item $FullFileName $FullFileName -ErrorVariable LockError -ErrorAction Stop
    $IsAccessible = $true
  }
  catch
  {
    $IsAccessible = $false
  }
  return $IsAccessible
}
1
  • 1
    Add some comments to your answer.
    – HDJEMAI
    Feb 21, 2017 at 23:37
1

SInce you don't want to read the file, I would recommend using a utility like Sysinternals Handle.exe, which will spit out all open handles for a process. You can download Handle.exe from here:

http://technet.microsoft.com/en-us/sysinternals/bb896655

You can run Handle.exe without any arguments, and it will return all open file handles. You can parse the output if necessary, or just match the output against your full file path.

1

Check this script on poschcode.org:

filter Test-FileLock {
    if ($args[0]) {$filepath = gi $(Resolve-Path $args[0]) -Force} else {$filepath = gi $_.fullname -Force}
    if ($filepath.psiscontainer) {return}
    $locked = $false
    trap {
        Set-Variable -name locked -value $true -scope 1
        continue
    }
    $inputStream = New-Object system.IO.StreamReader $filepath
    if ($inputStream) {$inputStream.Close()}
    @{$filepath = $locked}
}
4
  • FYI that's not a PoshCode link.
    – user189198
    Feb 22, 2012 at 15:51
  • Thanks, with the helping of the link, I created a new function which does what is required.
    – user983965
    Feb 22, 2012 at 18:43
  • 2
    @user983965, if you were able to solve your problem you should post the solution as an answer on SO. Links to solutions are less useful because the target page can change or disappear. Feb 22, 2012 at 19:14
  • @DourHighArch or be a bad website Nov 8, 2017 at 21:07
1

I want to correct above answer:

 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]::None )
            write-host (getDateTime) "[ACTION][FILEAVAILABLE]" $filePath
            $fileStream.Dispose()
            return $true
        }
        catch
        {
            write-host (getDateTime) "[ACTION][FILELOCKED] $filePath is locked"
            return $false
        }
    }

If you try to open file with [FileShare]::Read, it could be opened if other process also specified this (or less restricitve) FileShare mode. So, you must use [FileShare]::None, as most restrictive and incompatible with any other mode - so if file opened by another process in any way, it will be failed to open by script.

Also filestream should be disposed, otherwise file may remain opened for indefinite amount of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.