3

I'm trying to get FQDN of a host in some .cmd file. We have disjointed AD domain so "@echo %COMPUTERNAME%.%USERDNSDOMAIN%" does not work. I mean it works, but returns wrong value.

The solution I ended up with is powershell.exe -noninteractive -command[System.Net.Dns]::GetHostByName(($env:computerName)).HostName

It works fine in the command line. I'm trying to get it in a variable in my cmd file:

FOR /F "tokens=* USEBACKQ" %%F IN (\`powershell.exe -noninteractive -command     
[System.Net.Dns]::GetHostByName(($env:computerName)).HostName\`) DO (
    SET var=%%F
)
ECHO %var%

But getting the following error: ).HostName`) was unexpected at this time.

I understand that something should be screened since both cmd and powershell are parsing this line, but do not know what to screen and how. How to make this get to work?

  • Quote the right-parens with hat: ^)^). Also the backquotes should not be preceded by backslashes; I assume/hope that is an artifact of trying to markdown for Stack. – dave_thompson_085 Jul 11 '18 at 10:34
5

You need to escape parenthesis inside the subject when using FOR \F

FOR /F "tokens=* USEBACKQ" %%F IN (`powershell.exe -noninteractive -command [System.Net.Dns]::GetHostByName^(^($env:computerName^)^).HostName`) DO (
    SET var=%%F
)

ECHO %var%
| improve this answer | |
  • this works, but not on the command line. I tried to do it on the command line first, but that didnt work. Once I did it in a bat file, worked flawlessly – PBo Feb 1 '19 at 11:17
  • To make this work in a command line, you must put only one % in front of the F variable. %% in a batch file. – Nic3500 Oct 2 '19 at 19:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.