检查相同的 powershell 脚本是否已经在运行,如果是,请稍后运行

问题描述

我通过远程服务器上的 ssh (apache) Powershell 脚本从我的 Java EE 应用程序调用,此脚本无法并行运行,因此我需要检查脚本是否已在运行并等待直到没有进程并运行该脚本等待脚本。脚本可能会被多次调用,例如。在几秒钟内运行 20 次,所有这些都需要一个一个地运行。

知道如何实现这一目标,或者这是否可能?谢谢!

解决方法

我在一些脚本中完成此操作的方法是使用锁定文件

  $lockFile = "$PSScriptRoot\LOCK"
    if (-not (Test-Path $lockFile)) {
        New-Item -ItemType File -Path $lockFile | Out-Null
       
        #  Do other stuff...
    
        Remove-Item -Path  $lockFile -Force
    }

你可以修改成这样吗?

$lockFile = "$PSScriptRoot\LOCK"
while (Test-Path $lockFile)
{
    Start-Sleep -Seconds 2
}

New-Item -ItemType File -Path $lockFile | Out-Null

#  Do other stuff...

Remove-Item -Path  $lockFile -Force