Assure only 1 instance of PowerShell Script is Running at any given Time

后端 未结 6 1455
小蘑菇
小蘑菇 2021-01-17 12:31

I am writing a batch script in PowerShell v1 that will get scheduled to run let\'s say once every minute. Inevitably, there will come a time when the job needs more than 1 m

6条回答
  •  -上瘾入骨i
    2021-01-17 13:15

    $otherScriptInstances=get-wmiobject win32_process | where{$_.processname -eq 'powershell.exe' -and $_.ProcessId -ne $pid -and $_.commandline -match $($MyInvocation.MyCommand.Path)}
    if ($otherScriptInstances -ne $null)
    {
        "Already running"
        cmd /c pause
    }else
    {
        "Not yet running"
        cmd /c pause
    }
    

    You may want to replace

    $MyInvocation.MyCommand.Path (FullPathName)
    

    with

    $MyInvocation.MyCommand.Name (Scriptname)
    

提交回复
热议问题