title: File Lock Mechanism using PowerShell
body: <p>I have two processes that reads from the same file. I want to make sure that those two processes doesn't run at the same. My approach is that , when a process starts, it should look for a file(process.txt). If the file doesn't exist, it creates the file and continue execution, reading from the shared file(sharedfile.txt) between the two processes.  It then deletes the process.txt file after executing.</p>
  <p>Since both process deletes process.txt file after execution, if the file exists,it should go into a start sleep until the other process finishes and deletes the file.</p>
  <p>The problem here is when one process finishes and deletes the file(process.txt), the other still stay in the loop without executing even if no file exists. I am not sure of the right loop to use. I tried a couple of them and couldn't achieve my goal.</p>
  <pre><code>Clear Host
  $sleeptime = 15
  $lockfile = &quot;C:\Users\processid.txt&quot;
  $file = test-path -Path $lockfile
  Try
  {
  if($file -eq 'True')
  {
  echo “Lock file found!”
  echo &quot;This means file is being used by another process&quot;
  echo &quot;Wait for file to be deleted/released&quot;
  echo “Sleeping for $sleeptime seconds”
  Start-Sleep $sleeptime -Verbose
  }
  else
  {
      New-item -Path $lockfile
      #Executing a code here
  }
      Remove-Item $lockfile –Force
  }
  }
  Catch
  {
  Write-Host $_.Exception.Message`n
  }
  </code></pre>