0

The below thread explains how to check for more than 1 instance of a powershell script using get-wmiobject win32_process

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

For get-wmiobject win32_process to list a running powershell script, that script needs to be invoked using powershell.exe scriptName.ps1. How can I check for more than 1 instance of the script running where the script was invoked using .\scriptName.ps1?

3
  • 1
    Your GWMI call is the same as Get-Process essentially. All it tells you is whether the powershell.exe process is running, not whether a specific script is running. Commented Nov 14, 2017 at 21:01
  • If I had to guess, what you really want is a Mutex... Commented Nov 14, 2017 at 21:09
  • On the contraty, GWMI allows me to see not only that the powershell.exe process is running but also shows me the exact commandline (i.e. with arguments), whereas Get-Process only shows me that the powershell.exe is running Commented Nov 16, 2017 at 1:47

1 Answer 1

0

You could use the below and see if the result is > 1

(Get-WmiObject Win32_Process | select commandline | where {$_ -ilike "*scriptName.ps1*"} | measure).Count
Sign up to request clarification or add additional context in comments.

3 Comments

That could work but has 2 problems: 1- If someone opens a powershell window and then runs the script from the cmd line, this won't detect it. 2 - If someone tries to edit it, by say typing notepad scriptName.ps1, you'll get a false positive.
Comparison operators are case-insensitive by default. I'm really not sure why they made explicit operators for it
Get-WmiObject Win32_Process requires that one invoke a powershell script using "powershell.exe <scriptName>", like @zdan said

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.