Search code examples
windowspowershellpowershell-4.0powershell-remoting

Restricting one instance of PS Script when all parms are same


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%'"

Solution

  • 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.