开发者

How can I ensure only one instance of a script is running at a time?

开发者 https://www.devze.com 2023-02-01 06:18 出处:网络
Suppose I laun开发者_JS百科ch a powershell script and it\'s running in a loop. I open a second ps console and launch a second script. In this script I want to detect if the first script is running or

Suppose I laun开发者_JS百科ch a powershell script and it's running in a loop. I open a second ps console and launch a second script. In this script I want to detect if the first script is running or not. What are the ways to achieve this?


If you're looking at opening 2 separate consoles, you'll need to add some logic in your script to do some changes to the file system, registry or even the title bar of your PowerShell session where it is running. Then you can use some logic in your 2nd console to look for that information.

One other method, that I typically use, is with WMI:

PS>get-wmiobject win32_process|where {$_.name -eq "powershell.exe"}|select-exp commandline

An example:

CommandLine                : powershell.exe -file "./loop.ps1"

This means that you need to call powershell.exe to run your script though.


When only interested in processes on my local computer, I would use

get-process *powershell*

I want to get PowerShell ISE too, therefore the wildcard.


I had to do the same and wrote a module that uses a mutex to restrict script invocation to a single instance. To use it, you call the Enter-SingleInstance function that returns true if this is the first script instance invoking it or false if it is not the first instance (by default, it uses the script path to identify the script instance, but you can use a custom identifier, such as GUID). At the end, you need to call Exit-SingleInstance to release the mutex, e.g.:

if (!(Enter-SingleInstance)) {
    throw "The script is already running."
}
else {
    try {
        # Do what you need to do.
    }
    finally {
        # Make sure you exit single instance on both success and failure.
        Exit-SingleInstance
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消