Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 限制同一脚本的多次执行_Powershell_Powershell 2.0_Powershell 3.0 - Fatal编程技术网

Powershell 限制同一脚本的多次执行

Powershell 限制同一脚本的多次执行,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,我已尝试在PowerShell中限制同一脚本的多次执行。我尝试了以下代码。现在它正在工作,但一个主要缺点是,当我关闭PowerShell窗口并尝试再次运行同一个脚本时,它将再次执行 代码: 如何避免此缺点?我想您应该确保脚本不是从不同的powershell进程运行的,也不是从与某种自我调用相同的进程运行的 在这两种情况下,powershell中都没有这方面的内容,因此您需要模拟信号量 对于相同的过程,您可以利用全局变量并将脚本包装在try/finally块周围 $variableName="So

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

代码:


如何避免此缺点?

我想您应该确保脚本不是从不同的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
}
现在,如果您想做同样的事情,那么您需要在流程之外存储一些东西。使用
测试路径
新项目
删除项目
创建一个具有类似思维方式的文件是个好主意


在这两种情况下,请注意,这种模拟信号量的技巧没有实际信号量那么严格,并且可能会泄漏。

这是一种非常奇怪的检测“是否已运行此脚本”的方法。[咧嘴笑]更常见的方法似乎是将文件放在某个地方并进行检查。另一种方法是写入事件日志并读取日志,以查看是否已经存在此类事件但是,我怀疑我会使用powershell作业&队列或PoshRSJobs模块及其限制选项。为什么还要阻止脚本再次运行?使脚本幂等通常是更好的方法(即确保脚本的结果即使在重新运行时也是相同的)。@arj-不客气!很高兴能帮助。。。祝你好运![咧嘴笑]
$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
}