I need to create a batch script that opens chrome in new window with an url address, then return its ProcessId. I've tried with other applications like notepad , it works fine but with chrome it always returns ProcessId = 0
ProcessId: 28388 (notepad is opened with specified file)
@echo off
set pid=0
for /f "tokens=2 delims==; " %%a in ('wmic process call create "notepad.exe Dummy.txt"^,"%~dp0." ^| find "ProcessId"') do set pid=%%a
echo ProcessId: %pid%
pause>nul
ProcessId: 0 (nothing happens then)
@echo off
set pid=0
for /f "tokens=2 delims==; " %%a in ('wmic process call create "chrome.exe https://www.google.com"^,"%~dp0." ^| find "ProcessId"') do set pid=%%a
echo ProcessId: %pid%
pause>nul
Any solution for this ? thank you in advance
CodePudding user response:
I'd advise that you use the following template which uses more robust syntax:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "Exec=%ProgramFiles%\Google\Chrome\Application\chrome.exe"
Set "Args=https://www.google.com"
Set "WDir=%~dp0."
Set "ProcessId="
For /F "Delims=;" %%G In ('^"%SystemRoot%\System32\wbem\WMIC.exe Process Call
Create '"%Exec%" "%Args%"'^,'%WDir%' 2^>NUL
^| %SystemRoot%\System32\findstr.exe /R "\<ProcessId\>"^"') Do Set /A %%G
(Set ProcessId) 2>NUL
Pause
Obviously the bottom two lines are included just to show you the successful variable name and value.
Please replace only the strings between the =
and closing doublequote on lines 4
, 5
and 6
, as necessary. Please ensure that those strings themselves do not include doublequotes, or end with trailing backward slashes.