Search code examples
batch-filewmic

How to remove unwanted spaces from new file created from variable in batch


This Works fine when run as Admin from anywhere except Root. It works saved as ANSI from Notepad - Unicode produces no output at all.

This Batch functions to create a new text file containing a directory listing of the Root using the volumeID as a variable in the filename. Note that running from a subdir circumvents the protected root from writing when UAC is on

PROBLEM IS: The created filename is padded with 12 extra spaces before the ext.

Question is: How to truncate the spaces or prevent them from being appended?

Rem BATCH CODE:---------------------------

Rem -----------Fetch VolumeID as Variable to use in output filename:

@echo off
wmic logicaldisk where drivetype=3 get volumeserialnumber
For /F "Skip=1 Delims=" %%j In ('WMIC LogicalDisk Where "DeviceID='%~d0'" Get VolumeSerialNumber') do (
  set v_VolID=%%j
  goto :DONE
)
:DONE
echo  SERIAL=%v_VolID%
echo %v_VolID%
Pause

rem --------- WRITE VolID.txt with Directory Listing
c:
cd\
dir *.*>"_____TEST Volume ID-%v_VolID%.txt"
endlocal & set "%2=%label_%" & goto :EOF

Solution

  • Replace your For loop with this:

    For /F "Skip=1 Delims=" %%A In (
        'WMIC LogicalDisk Where "DeviceID='%~d0'" Get VolumeSerialNumber'
    ) Do For /F %%B In ("%%A") Do Set "v_VolID=%%B"