限制同一脚本的多次执行

时间:2019-04-11 03:59:20

标签: powershell powershell-v2.0 powershell-v3.0

我试图在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"
}

如何避免这种缺点?

1 个答案:

答案 0 :(得分: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
}

现在,如果要执行相同的操作,则需要在过程之外存储某些内容。使用Test-PathNew-ItemRemove-Item,以类似的思路创建文件是一个好主意。

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

相关问题