Check if file is used before writing with PowerShell

When you are working in an infrastructure and want to gather information from multiple machines in a single file, somewhere on a sharepoint, you will encounter a major problem, and that is that you can’t write in a file from multiple machines at the same time. Even on your own machine, if a file has a writing operation from one application and you try to write to it from another application, this will result in an error.

Let’s say i have a file called Information.txt on the Desktop, and I have the next PowerShell script which writes into it:

for($i=1;$i -le 10000; $i++){

    Add-Content -Path "C:\Users\YOURUSER\Desktop\Information.txt" -Value "hello"

If I run this script, until it finishes, I cannot perform any other operations in the Information.txt file. So if I want to check if any operations are executed on a particular file, wait a period of time, check again, and only if no other operations are executed I will start writing into it, the next PowerShell code can be used:
function Check-FileOpen {

    param (




    $oFile = New-Object System.IO.FileInfo $Path

    if ((Test-Path -Path $Path) -eq $false)







        $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)

        if ($oStream)








      # file is locked by a process.




while ((Check-FileOpen -Path "C:\Users\theje\Desktop\Information.txt")){

Start-Sleep -s 15

   Write-Host "File in Use"


   Write-Host "File Not in Use"

Add-Content -Path "C:\Users\YOURUSER\Desktop\Information.txt" -Value "File Is Closed"
This function tries to open the file using System.IO, and if the operation fails it is interpreted as the file is currently in use. While the file is opened, we wait 15 seconds until the next check, and if the file is no longer opened, we write as a last line “File Is Closed”.
So, if we start writing in the Information.txt and run this script, the following will be outputed:
As a small disclaimer, this script will only check if a file is in use at the moment of execution, not if the file is opened by a program (for example notepad).

Leave a comment

Your email address will not be published. Required fields are marked *

3 × 2 =