限制同一脚本的多次执行

Restrict multiple executions of the same script

我试图在 PowerShell 中限制同一脚本的多次执行。我试过下面的代码。现在它可以工作了,但一个主要缺点是当我关闭 PowerShell window 并尝试再次 运行 相同的脚本时,它会再次执行。

代码:

$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"
}

如何避免这个缺点?

我想你想确保脚本不是 运行 来自不同的 powershell 进程,也不是来自与某种自调用相同的进程。

在任何一种情况下,powershell 中都没有这方面的任何内容,因此您需要模仿信号量。

对于相同的进程,您可以利用一个全局变量并将您的脚本包裹在一个 try/finally 块周围

$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
}

现在如果你想做同样的事情,那么你需要在你的进程之外存储一些东西。使用 Test-PathNew-ItemRemove-Item 具有类似思维方式的文件将是一个好主意。

无论哪种情况,请注意这个模仿信号量的技巧并不像实际信号量那样严格,并且可能会泄漏。