stringwindowsbatch-filedelimiternet-use

Windows batch/cmd file to extract network drives (strings between delimiters)?


I have backed up the network drive to an xml file in the format below.

<drive>
    <drive letter>X</drive letter>
    <drive path>\\DANIEL-HP\Users\Public\Documents\Downloaded Data Sheets</drive path>
</drive>

<drive>
    <drive letter>Y</drive letter>
    <drive path>\\DANIEL-HP\Users\Public</drive path>
</drive>

I want to run a batch or cmd file to extract the drive letter and path from between the delimiters and then map them.

For simplicity sake let's ignore whether other drives are mapped or not.

Delimiters for drive letter are <drive letter> and </drive letter> . Delimiters for drive path are <drive path> and </drive path>

I am not sure on how to parse the / <> symbols.


Solution

  • That's quite straight with a simple for loop:

    for /f "tokens=3 delims=<>" %%a in ('find "<drive letter>" test.xml') do echo %%a
    

    No need to escape > and <, because they are safe within the quotes.

    edit
    build up two "arrays" (1) for letter and path, then join them to get the desired result:

    @ECHO off
    setlocal enabledelayedexpansion
    REM get drives:
    set c=0
    for /f "tokens=3 delims=<>" %%a in ('find "<drive letter>" t.xml') do (
      set /a c+=1
      set drv-!c!=%%a
    )
    REM set paths:
    set c=0
    for /f "tokens=3 delims=<>" %%a in ('find "<drive path>" t.xml') do (
      set /a c+=1
      set pth-!c!=%%a
    )
    
    for /l %%x in (1,1,%c%) do echo !drv-%%x! !pth-%%x!
    

    (1) quoted because of the comments on this answer