How to determine the name of a running script?

I have written an HTTP listener and want to ensure it is always running. My current idea is to run it from Task Scheduler. The Task Scheduler will launch the script every 5 minutes. When the script first starts (before it tries to bind to the port for listening), it checks to see if it is already running. If so, then this instance of the script exits; otherwise it proceeds.

Get-Process will show the processes whose ProcessName is “powershell” but I can’t find a way to see which script a given powershell process is running (i.e. the -file argument used in TaskScheduler). Thus, I can’t determine if the script should exit or not.

I’m open to other ways of accomplishing the goal. However, the alternatives I’ve found (various ways to turn a PS script into a Windows service) are more complex or costly than I’m prepared to do at this time.

You can use CIM to achieve this.

Get-CimInstance -ClassName Win32_Process | Select-Object CommandLine

You can apply filter to this parameter, use -Filter option of Get-CimInstance cmdlet.

Hi Darin,

You may want to take a look at the Get-Job Start-Job Receive-Job Cmdlets. They may be what you need to accomplish this task.

Get-Job has a State property that you can monitor and wait for the job to complete.

Receive-Job will return the results of the script or command.