21 Nov 2009

How to implement a file based locking mechanism within a powershell script

The following code enables a file based locking mechanism within a powershell script. It checks for existance of a lock file and checks if a running process exists, which is capturing this file. This can be used in situations, where a script is beeing launched paralell by another script or programm, but you want to have your script executed exclusively and serialized.

The following code enables a file based locking mechanism within a powershell script. It checks for existance of a lock file and checks if a running process exists, which is capturing this file. This can be used in situations, where a script is beeing launched parallel by another script or programm, but you want to have your script executed exclusively and serialized.


#################################################
#Scriptname:     checklock.ps1
#Author:         Michael Rüefli (www.miru.ch)
#Date:           21.11.2009
#Description:    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
#
#Usage:          Paste your code in the MAIN section and set the $lockfile paramater to match your needs
############################################

$lockfile = “d:\lock.lck”
$lockstatus = 0
While ($lockstatus -ne 1)
{
If (Test-Path $lockfile)
{
echo “Lock file found!”
$pidlist = Get-content $lockfile
If (!$pidlist)
{
$PID | Out-File $lockfile
$lockstatus = 1
}
$currentproclist = Get-Process | ? { $_.id -match $pidlist }
If ($currentproclist)
{
echo “lockfile in use by other process!”
$rndwait = New-Object system.Random
$rndwait= $rndwait.next(1,4)
echo “Sleeping for $rndwait seconds”
Start-Sleep $rndwait
}
Else
{

Remove-Item $lockfile -Force
$PID | Out-File $lockfile
$lockstatus = 1

}
}
Else
{
$PID | Out-File $lockfile
$lockstatus = 1
}
}

#———————————————————————————————–
## Main Script Part
## Here you can paste your code, in fact what the script has to do
echo “Hi, it seems that no other script is doing the same as me now.. so I can do my job exclusively”

## End of Main Part
#———————————————————————————————–
#remove the lockfile
Remove-Item $lockfile –Force