Assure only 1 instance of PowerShell Script is Running at any given Time
powershell, windows
Solution
If the script was launched using the powershell.exe -File switch, you can detect all powershell instances that have the script name present in the process commandline property:
Get-WmiObject Win32_Process -Filter "Name='powershell.exe' AND CommandLine LIKE '%script.ps1%'"
Problem
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 minute to complete and now we have two instances of the script running, and then possibly 3, etc... I want to avoid this by having the script itself check if there is an instance of itself already running and if so, the script exits. I've done this in other languages on Linux but never done this on Windows with PowerShell. For example in PHP I can do something like: ``` exec("ps auxwww|grep mybatchscript.php|grep -v grep", $output); if($output){exit;} ``` Is there anything like this in PowerShell v1? I haven't come across anything like this yet. Out of these common patterns, which one makes the most sense with a PowerShell script running frequently? - Lock File - OS Task Scheduler - Infinite loop with a sleep interval