Duy Gonzales
Duy Gonzales

Reputation: 53

How do I add a variable to a file name in a batch file?

I want to redirect a file to a text file with a specific filename. The filename should be the serial number of the machine. I currently have the below command but for some reason, the output is different from what I want.

@echo off
set serial=wmic bios get serialnumber
set bit=manage-bde -status C:
%bit% > "C:\Users\Frangon\Desktop\%serial%.txt"
pause

It redirects the %bit% to a text file but the filename becomes wmic bios get serialnumber instead of the SERIAL NUMBER of the machine.

Please help as I'm stuck.

Upvotes: 0

Views: 4541

Answers (1)

Stephan
Stephan

Reputation: 56165

As said in a comment before, the way to get a command's output to a variable is a for /f loop. There is one quirk with wmic: it has unusual line endings CR CR LF. The first CR will be part of the variable and will cause bad things. One way to overcome that (and the most reliable way) is parsing the output with another for loop.

There is no need to assign the output of manage-bde -status C: to a variable (would be very difficult in batch anyway because it's more than one line). Just redirect the output directly to the file:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic bios get serialnumber /value') do for %%b in (%%a) do set "serial=%%b"
manage-bde -status C: > "%USERPROFILE%\Desktop\%serial%.txt"

Upvotes: 1

Related Questions