0

When I enter "hostname" into the Windows Command Prompt, I get the expected hostname of the system, but I can't seem to include it in any string output, either assigned to another variable, or just as itself.

The below script outputs "Ready to copy to Server of Is this the correct location?" and all variations of using hostname seem to result in the same.

@echo off 
set hostnamevar=%hostname%
set "greeting1=Ready to copy to Server of "
set "greeting2=Is this the correct location?"
set "greeting=%greeting1%%hostnamevar%%greeting2%"
echo %greeting%
pause 
4
  • 2
    Try for /f %%A in ('hostname') do set hostname=%%A. The hostname program is not an environment variable. This is one way to run the program and set the output as a variable. Every time I see code like this I'm reminded why I use Bash, even in Windows. Commented Sep 15, 2015 at 3:41
  • to understand, what is hostname here? a command? a variable? hostname /? give command unknown even with echo %hostname% but if I type hostname on console, it show a weird output. Server : UnKnown Address: 2001:4860:4860::8888 Commented Sep 15, 2015 at 3:47
  • Actually this post is very similar to this one (the second code snippet)... Commented Sep 15, 2015 at 12:41
  • 1
    Oh wait, my cmd was stuck in nslookup command, this is why the hostname command was not recognized, sorry. (I will remove all my comments in a short time) Commented Sep 15, 2015 at 18:18

1 Answer 1

2

Here, hostname is set as an environment variable now.

@ECHO OFF
FOR /F %%H IN ('hostname') DO SET hostnamevar=%%H
SET Greeting=Ready to copy to Server of "%hostnamevar%" Is this the correct location?
ECHO %Greeting%
PAUSE

A little note, on this section, SET Greeting=Ready to copy to Server of "%hostnamevar%" Is this the correct location? you don't need the encapsulating "" around %hostnamevar%

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure I follow on your comment. If the encapsulating quotations around %hostnamevar% aren't necessary, then why have them?
Just me being me in all honesty, if that were my code, I like my eye to be drawn to the variable just for verification that the variable is in fact changing. but the code will execute proper with simply inserting %hostnamevar% where ever you want, if you wanted to you could set the title of the batch window to the hostname. TITLE %hostnamevar%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.