4

I want to execute one command and assign it's value to a variable within a batch file.

We know that running hostname command on a windows command prompt gives the PC name. I want to use hostname command and assign it's value to a variable within a batch file.

After googling about it, I've tried using below methods, none of these seem to work:

set CONTROLLER=hostname
set CONTROLLER=%hostname%
set CONTROLLER=%%hostname%%
set CONTROLLER=!hostname!

Kindly advise.

Ayush
  • 909
  • 1
  • 13
  • 32

2 Answers2

4

We can easily get the hostname/computer name through below command

set host=%COMPUTERNAME%
echo %host%
1

Try Using

@echo off
for /f "delims=" %%a in ('hostname') do @set HOST=%%a
echo %HOST%
PAUSE

Where HOST is your variable and in place of 'hostname' you can use any other command you like as well.

nishantvas
  • 184
  • 3
  • 16
  • 1
    http://stackoverflow.com/questions/889518/windows-batch-files-how-to-set-a-variable-with-the-result-of-a-command – nishantvas Mar 21 '17 at 06:36
  • I did came across this one, was looking for a less complex method to do this. See Rajesh's answer as well, I realize that'd work only for 1 particular command, but hey that's what I need right now. Thanks anyway – Ayush Mar 21 '17 at 06:42