PoshCode Logo PowerShell Code Repository

PS file locking by drmiru 4 years ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1566"></script>download | new post

The code uses a file locking mechanism to ensure that the
script beeing started is running exclusively. Mostly used where
a powershell script is started parallel within a few seconds

  1. #################################################
  2. #Scriptname:     checklock.ps1
  3. #Author:         Michael Rόefli (www.miru.ch)
  4. #Date:           21.11.2009
  5. #Description:    The code uses a file locking mechanism to ensure that the
  6. #                script beeing started is running exclusively. Mostly used where
  7. #                a powershell script is started parallel within a few seconds
  8. #
  9. #Usage:          Paste your code in the MAIN section and set the $lockfile paramater to match your needs
  10.  
  11. ############################################
  12.  
  13. $lockfile = “d:\lock.lck”
  14. $lockstatus = 0
  15. While ($lockstatus -ne 1)
  16. {
  17.         If (Test-Path $lockfile)
  18.         {
  19.                 echo “Lock file found!”
  20.                 $pidlist = Get-content $lockfile
  21.                 If (!$pidlist)
  22.                 {
  23.                         $PID | Out-File $lockfile
  24.                         $lockstatus = 1
  25.                 }
  26.                 $currentproclist = Get-Process | ? { $_.id -match $pidlist }
  27.                 If ($currentproclist)
  28.                 {
  29.                         echo “lockfile in use by other process!”
  30.                         $rndwait = New-Object system.Random
  31.                         $rndwait=       $rndwait.next(500,1000)
  32.                         echo “Sleeping for $rndwait Milliseconds”
  33.                         Start-Sleep -Milliseconds $rndwait
  34.                 }
  35.                 Else
  36.                 {
  37.                         Remove-Item $lockfile -Force
  38.                         $PID | Out-File $lockfile
  39.                         $lockstatus = 1
  40.                 }
  41.         }
  42.         Else
  43.         {
  44.                 $PID | Out-File $lockfile
  45.                 $lockstatus = 1
  46.         }
  47. }
  48.  
  49. #———————————————————————————————–
  50. ## Main Script Part
  51. ## Here you can paste your code, in fact what the script has to do
  52. echo “Hi, it seems that no other script is doing the same as me now.. so I can do my job exclusively”
  53.  
  54. ## End of Main Part
  55. #———————————————————————————————–
  56. #remove the lockfile
  57. Remove-Item $lockfile -Force

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me