Search code examples
javabatch-filewmic

Wmic process call in for loop doesn't start the cmd


I am trying to retrieve the ProcessID of a Java app launched through a batch file. The problem is that the application does not start.

My code:

set cmd=java -jar XXXXXXX.jar XXXXXX.yml
for /f "tokens=2 delims==; " %%a in (' wmic process call create "%cmd%" ^| find "ProcessId" ') do set PID=%%a
start cmd /k echo %pid%
PAUSE

Solution

  • Batch files are pretty picky with whitespace.

    Change this:

    set cmd = java -jar XXXXXXX.jar XXXXXX.yml
    

    To this:

    set cmd=java -jar XXXXXXX.jar XXXXXX.yml
    

    This works:

    set cmd=notepad
    
    for /f "tokens=2 delims==; " %%a in (' wmic process call create "%cmd%" ^| find "ProcessId" ') do set PID=%%a
    
    start cmd /k echo %pid%
    
    PAUSE
    

    There may be something wrong with your jar file or perhaps java is not on your PATH. Try running your command directly at a command prompt to see if it works:

    c:\>java -jar XXXXXXX.jar XXXXXX.yml
    

    Also make sure that you use the full path to your jar file in your cmd otherwise the path will be relative to your system folder:

    set cmd=java -jar c:\yourpath\XXXXXXX.jar XXXXXX.yml