Question

I need to identify the P(rocess) ID of an executing batch file from a PowerShell (v1.0) script. Can anyone suggest a way of doing this?

Thanks, MagicAndi.

Was it helpful?

Solution

Well, whether that's possible depends on how you executed the batch file.

In general, the only way you could possibly find this out is to look at the command line used to start the batch. If you double-click a batch file in Windows Explorer you'll get a command line like

cmd /c ""C:\Users\Me\test.cmd" "

In Powershell you can then use Get-WMIObject on Win32_Process which includes the command line:

PS Home:\> gwmi Win32_Process | ? { $_.commandline -match "test\.cmd" } | ft commandline,processid -auto

commandline                             processid
-----------                             ---------
cmd /c ""C:\Users\Me\test.cmd" "             1028

However, if you started the batch directly from a command prompt, then you have no way of externally finding out that a batch is running and who started it.

OTHER TIPS

I have found one method of discovering the PID of a running batch file. You will need to set the title of the batch console window in the batch file to identify it:

...
Title MyBatchWindow
...

In the PowerShell script, you can check for the MainwindowTitle property and retrieve the PID from the process that matches your batch window title:

$batchProcess = get-process cmd | where-Object {$_.MainWindowTitle -eq "MyBatchWindow"}
$processID = $batchProcess .ID
...

I have tested this method, and it appears to work both where you call the batch file by double clicking it, or by calling it from the command line.

I don't believe this is possible in a reliable manner. Batch files themselves do not launch a separate process but instead are run within a cmd.exe instance. There is no exported data from that particular process that will reliably tell you what file is being run.

The one exception is if a cmd.exe instance is launched specifically to run a batch file. In that case it would appear in the command line of the application and it would be possible to grep the command line for the batch file. This wouldn't solve the normal case though of multiple batch files being run from within a cmd.exe prompt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top