0

im having difficulties trying to set the output of the hostname command as a variable. what I want to do is to have the text file that is outputted to have the name of the computer so computer1.txt, computer2.txt etc, but i want to do it without making a temp file for example

    set HNAME =`hostname` 

this is what i have currently but the script i am using is being run on several computers at the same and i believe that the temp file that i create is causing issues with the names of the .txt files.

    hostname >> hostname.txt


    set /p HNAME=<hostname.txt 

    pause

    echo hello > %HNAME%.txt
    pause
  • possible duplicate of [Windows batch files: How to set a variable with the result of a command?](http://stackoverflow.com/questions/889518/windows-batch-files-how-to-set-a-variable-with-the-result-of-a-command) – npocmaka Jun 18 '14 at 19:24
  • And [Windows Batch help in setting a variable from command output](http://stackoverflow.com/q/1746475) and [Batch File - Set command output as variable](http://stackoverflow.com/q/23028318) – Ken White Jun 18 '14 at 19:28
  • Be very careful with string-assignments in batch. `set` and `set /p` are sensitive to spaces on **both** sides of the `=`. Your `set HNAME =...` would set a variable called "HNAMEspace" and also include any trailing spaces on the line in the value assigned, which can be hard to spot. `set "HNAME=value"` safely ignores trailing spaces. Note also that other than the enclosing rabbits ears in `set "HNAME=value"`, any "quotish" character is included literally in the value assigned. – Magoo Jun 19 '14 at 00:20

1 Answers1

1

You have to use the for command, something like this:

for /f "usebackq" %i in ( `somecommand` ) do set envar=%i

It's very painful. for /? at the command line for more information.

Rob K
  • 8,757
  • 2
  • 32
  • 36
  • for use in a batchfile write `%%i` instead of `%i` (both occurencies). – Stephan Jun 18 '14 at 19:45
  • `usebackq` in this case will turn `'somecommand'` into string but not in processed command.``` should be used.And more - it will assign to `envar` only the first word of the result. – npocmaka Jun 18 '14 at 20:17