Question-er XDD
Question-er XDD

Reputation: 767

Windows Batch - read result from cmd command and save to a variable

I would like to read the hostname of my device and generate a file with such name. However, I am new in Windows Batch, I don't even understand how to use of those variable, read file......

Here is what I want to do:

CD C:\WINDOWS\SYSTEM32\
CMD.EXE hostname -> to a HostName variable e.g. called abc ::I hope it will save my computer name to a variable string
echo It success to function >> C:\%abc%.txt :: I hope it can generate a file with the sting in variable
PAUSE

I have thought that if it is not function with cmd command, so I tried the alternative method:

CD C:\WINDOWS\SYSTEM32\
CMD.EXE hostname >> C:\HostName.tmp
-AND THEN READ BACK the C:\HostName.tmp Here
-And then save to a variable again e.g. 
echo It success to function >> C:\HostName_variable.txt ::It generate a file with the sting in variable
PAUSE

It seems not successful =[.

Added: I would like to create a file with the name of hostname. e.g. if my hostname is "abc", it will output a file as "abc.csv" something like this.

Upvotes: 1

Views: 6412

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

You can get it two ways:

Environment variables are a few pre-configured variables containing general system state, and one of them is COMPUTERNAME, which you can send straight to a file like:

echo %COMPUTERNAME% > hostname_file.txt

Or you can store it in another variable, first, then echo the content of that variable to a file:

set myHostName=%HOSTNAME%
echo %myHostName% > hostname_file.txt

The other way is running the hostname.exe program which prints the current computer name, and redirect the output to a file:

hostname > hostname_file.txt

It's harder to run hostname.exe and store the result in a variable, you need to abuse a for loop to do that:

for /f %f in ('hostname') do set myHostName=%f
echo %myHostName% > hostname_file.txt

NB. What you are doing isn't quite how you describe it - a file isn't the same thing as a variable:

You write:

CD C:\WINDOWS\SYSTEM32\
CMD.EXE hostname >> HostName_variable ::It will save my computer name to a variable string
echo It success to function >> C:\HostName_variable.txt ::It generate a file with the string in variable
PAUSE

cmd.exe is unnecessary because you're already in a command prompt when you run it, you don't need another one to run. You don't need to change to c:\windows\system32 first, because Windows always looks there for programs to run. >> is adding to the end of a file if it exists, it won't always create a new file, > will always create a new file and if one already exists, will overwrite it. Once it has sent the output to a file, it's not in a variable.

Upvotes: 3

Related Questions