Samot
Samot

Reputation: 47

Check if the same powershell script is already running and run it later if yes

I am calling from my Java EE application through ssh (apache) Powershell script on remote server, this script cannot be run in parallel so I need to check if the script is already running and wait until there is no process and run that waiting script. It might happen that the script will be called several times, eg. 20 times in few seconds and all of these needs to be run one by one.

Any idea how this can be achieved or if this is even possible? Thank you!

Upvotes: 0

Views: 907

Answers (1)

Daniel
Daniel

Reputation: 5114

The way that I've accomplished this in some of my scripts is to use a lock file

  $lockFile = "$PSScriptRoot\LOCK"
    if (-not (Test-Path $lockFile)) {
        New-Item -ItemType File -Path $lockFile | Out-Null
       
        #  Do other stuff...
    
        Remove-Item -Path  $lockFile -Force
    }

You could maybe modify to something like this?

$lockFile = "$PSScriptRoot\LOCK"
while (Test-Path $lockFile)
{
    Start-Sleep -Seconds 2
}

New-Item -ItemType File -Path $lockFile | Out-Null

#  Do other stuff...

Remove-Item -Path  $lockFile -Force

Upvotes: 2

Related Questions