限制同一脚本的多次执行

问题描述 投票:1回答:1

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

码:

$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-v2.0 powershell-v3.0
1个回答
1
投票

我假设您要确保脚本不是从不同的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
}

现在,如果你想做同样的事情,那么你需要在你的过程之外存储一些东西。使用qazxsw poi,qazxsw poi和qazxsw poi,使用类似的思维模式是一个好主意。

在任何一种情况下,请注意这个模仿信号量的技巧,并不像实际的信号量那样严格并且可能泄漏。

© www.soinside.com 2019 - 2024. All rights reserved.