arj
arj

Reputation: 983

Restrict multiple executions of the same script

I have tried to restrict multiple executions of the same script in PowerShell. I have tried following code. Now it is working, but a major drawback is that when I close the PowerShell window and try to run the same script again, it will execute once again.

Code:

$history = Get-History
Write-Host "history=" $history.Length
if ($history.Length -gt 0) {
    Write-Host "this script already run using History"
    return
} else {
    Write-Host "First time using history"
}

How can I avoid this drawback?

Upvotes: 1

Views: 586

Answers (1)

Alex Sarafian
Alex Sarafian

Reputation: 674

I presume you want to make sure that a script is not running from different powershell processes, and not from the same one as some sort of self-call.

In either case there isn't anything in powershell for this, so you need to mimic a semaphore.

For the same process, you can leverage a global variable and wrap your script around a try/finally block

$variableName="Something unique"
try
{
  if(Get-Variable -Name $variableName -Scope Global -ErrorAction SilentlyContinue)
  {
     Write-Warning "Script is already executing"
     return
  }
  else
  {
     Set-Variable -Name $variableName -Value 1 -Scope Global
  }
  # The rest of the script
}
finally
{
   Remove-Variable -Name $variableName -ErrorAction SilentlyContinue
}

Now if you want to do the same, then you need to store something outside of your process. A file would be a good idea with a similar mindset using Test-Path, New-Item and Remove-Item.

In either case, please note that this trick that mimics semaphores, is not as rigid as an actual semaphore and can leak.

Upvotes: 2

Related Questions