Parsing protocol parameter (URL) in batch file?

2

I'm trying to use a .bat file as a protocol handler. The protocol URL for example is testapp://close and I set the protocol to launch "C:\test.bat" "%1" in the registry.

The test.bat file

@echo off
echo %1
pause
exit 0

Essentially what I want to do is just pass the parameter in the URL close to some application to execute C:/someapp.exe close however the %1 parameter I get is the full url testapp://close/. How can I parse the close parameter out of the %1 variable using only native Windows commands?

Matt

Posted 2019-01-16T16:35:29.127

Reputation: 215

Try this: explorer.exe testapp://close – Biswapriyo – 2019-01-16T16:47:27.047

Answers

2

You can use a FOR /F loop and with the options "TOKENS=2 DELIMS=/" you can get the value from the URL string passed in as the first argument at batch script execution after its (the URL value) second forward slash (/) but before the next forward slash (/) giving you the expected result exactly as you describe you need from that part of the URL.

You can SET the parsed URL string as a variable value and use that to pass as the first argument to the application executable file. I'll put a couple batch script examples below to help further clarify.


#1. Batch Script

@echo off
echo %~1
FOR /F "TOKENS=2 DELIMS=/" %%A IN ("%~1") DO (SET "var=%%~A")
echo %var%
pause
exit 0

#2. Batch Script

@ECHO OFF
FOR /F "TOKENS=2 DELIMS=/" %%A IN ("%~1") DO (CALL C:/someapp.exe "%%~A")
EXIT 0

#1. Correlated Output Results

C:\Users\User\Desktop> test.bat "testapp://close/"
testapp://close/
close
Press any key to continue . . .

enter image description here


Further Resources

  • FOR /F
  • FOR /?

        delims=xxx      - specifies a delimiter set.  This replaces the
                          default delimiter set of space and tab.
        tokens=x,y,m-n  - specifies which tokens from each line are to
                          be passed to the for body for each iteration.
                          This will cause additional variable names to
                          be allocated.  The m-n form is a range,
                          specifying the mth through the nth tokens.  If
                          the last character in the tokens= string is an
                          asterisk, then an additional variable is
                          allocated and receives the remaining text on
                          the line after the last token parsed.
    

Pimp Juice IT

Posted 2019-01-16T16:35:29.127

Reputation: 29 425

@Matt For #2 Batch Script you might consider using FOR /F "TOKENS=2 DELIMS=/" %%A IN ("%~1") DO (START "" C:/someapp.exe "%%~A") to use start in place of call but I suspect you already know this but wanted to mention in a comment just in case. – Pimp Juice IT – 2019-01-17T04:22:20.713