Reputation: 15591
I am running the script with following parms:
test.ps1 -parm1 abc1 -parm2 abc2 -parm3 abc3
I am executing script remotely from my another application and want to run only one instance of the script when are parms are same.
In other words, if all parms are same then only one instance of the script should be running at any time.
I am using the following logic but it is returning null
Get-WmiObject Win32_Process -Filter "Name='powershell.exe' AND CommandLine LIKE '%test.ps1%'"
Upvotes: 0
Views: 441
Reputation: 131
I assume you want to prevent multiple instances of the script to be running simultaneously on 1 given host.
In that case, have your script create a so called 'lock file' (just some text file at a specified location of your choice)
At the beginning of your script, check if the file exists (if it does, another instance is running; bail out!) if it does not exist; create the lock-file, do your script business and at the end don't forget to delete the lock-file (unless the script is not allowed to run more than once on that computer)
Feel free to add additional information into the lock file (e.g. parameters being used, process-ID), to make even more versatile use of that file.
Upvotes: 0
Reputation: 16096
If you ran this...
WmiObject Win32_Process -Filter "Name='powershell.exe' AND CommandLine LIKE '%test.ps1%'"
… and it returned nothing, then that means it's not running or ran and closed.
I just tried what you posted and the above pulls the process line as expected.
# begin test.ps1 script
Param
(
$parm1,
$parm2,
$parm3
)
'hello'
# end test.ps1 script
# SCC is a alias for a function I have to shell out to the console host as needed
# aka Start-ConsoleCommand
# it has code to prevent the console host from closing so I can work in it if needed.
scc -ConsoleCommand '.\test.ps1 -parm1 abc1 -parm2 abc2 -parm3 abc3
# console window results
hello
Check the process info
Get-WmiObject Win32_Process -Filter "Name='powershell.exe' AND CommandLine LIKE '%test.ps1%'"
# Results
...
Caption : powershell.exe
CommandLine : "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit -Command &{ .\test.ps1 -parm1 abc1 -parm2 abc2 -parm3 abc3
...
Yet, your stated use case is kind of odd. As, since you are started the code in the first place, and you are saying, you only want it ran once, then why bother to start it again, just to check what you already know is running?
If you are saying, you need to run it multiple time sequentially, then do that sequentially.
If you are saying, that any user can use your app from any machine, then you'd still only have one running at a time from different machines, so the check really is moot. Unless you code is working (create-update-delete actions) on the same files/database, and trying to avoid errors when another users tries to use your code to act on it.
Upvotes: 1