Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the hostname in a variable in a .bat file?

People also ask

How do you put a title in a batch file?

Remarks. To create window title for batch programs, include the title command at the beginning of a batch program. After a window title is set, you can reset it only by using the title command.

How do you store hostname in a variable in PowerShell script?

FreeKB - PowerShell System hostname using the $env:computername variable. Often, you will store the hostname in a variable most likely named $hostname. If you want to append additional text to the hostname, wrap the variable in double quotes. In this example, the computer name is US-H2LXQ72.

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Can you use variables in batch files?

There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.


hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.


I usually read command output in to variables using the FOR command as it saves having to create temporary files. For example:

FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i

Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the % in the FOR statement by putting them twice:

FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%

There's a lot more you can do with FOR. For more details just type HELP FOR at command prompt.


I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

Why not so?:

set host=%COMPUTERNAME%
echo %host%