1

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?

3
  • 4
    that is a rather odd way to detect "has this script been run". [grin] the more common method seems to be to place a file somewhere & check for that. another is to write to the event log and read the log to see if there is such an event already there. ///// however, i suspect i would use powershell jobs & a queue OR the PoshRSJobs module & its throttling options. Commented Apr 11, 2019 at 4:06
  • Why do you even want to prevent the script from being run again? It's usually a better approach to make the script idempotent (i.e. ensure that the outcome of the script is the same even upon re-running it). Commented Apr 11, 2019 at 11:42
  • @arj - you are welcome! glad to help ... and good luck! [grin] Commented Apr 11, 2019 at 17:06

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.