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?

Manu
  • 1,685
  • 11
  • 27
Alex Rodrigues
  • 179
  • 1
  • 1
  • 6
  • 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. – Maximilian Burszley Nov 14 '17 at 21:01
  • If I had to guess, what you really want is a Mutex... – Kory Gill Nov 14 '17 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 – Alex Rodrigues Nov 16 '17 at 01:47

1 Answers1

-1

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

(Get-WmiObject Win32_Process | select commandline | where {$_ -ilike "*scriptName.ps1*"} | measure).Count
zdan
  • 28,667
  • 7
  • 60
  • 71
  • 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. – zdan Nov 14 '17 at 21:40
  • Comparison operators are case-insensitive by default. I'm really not sure why they made explicit operators for it – Maximilian Burszley Nov 14 '17 at 21:42
  • Get-WmiObject Win32_Process requires that one invoke a powershell script using "powershell.exe ", like @zdan said – Alex Rodrigues Nov 16 '17 at 01:49