How to find the PCs name in a batch script?

How would I find the name of the PC running my batch program on it?

I would like to find the name of a PC that is running my batch program and be able to store it as a variable. Any help?

3

3 Answers

As Vikas Gupta has answered, you can use the pre-defined %COMPUTERNAME% environment variable that already contains the computer name. From a practical stand point, this should be all you need.

However, it is possible for a batch file to over-write the value, so it is not guaranteed that the value be correct.

You can use WMIC to directly read the computer name.

for /f "skip=1 delims=" %%A in ( 'wmic computersystem get name'
) do for /f "delims=" %%B in ("%%A") do set "compName=%%A"

The extra FOR loop eliminates unwanted carriage return characters that are an artifact of FOR /F interacting with the Unicode output of WMIC. With only one loop there is a carriage return at the end of each line that can cause problems.

2

On Windows, typically an environment variable is already set and available for you to use -

echo %ComputerName%
5

In PowerShell you can also use:

[Environment]::MachineName

Here the value comes from .Net so it avoids the issue of using $Env:ComputerName.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like