4

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?

Kevin K.
  • 383
  • 1
  • 7
Papa Smurf
  • 81
  • 1
  • 3
  • 8
  • 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

1 Answers1

6

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%
Kevin K.
  • 383
  • 1
  • 7
  • 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 01 '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 02 '19 at 19:57