如何使用批处理命令将主机名替换为网络驱动器路径中的IP地址

时间:2017-04-06 14:20:39

标签: windows batch-file cmd

set SourceDir=\\my_server\path    

if "%SourceDir:~0,2%"=="\\" (
  set sourceHost= REM not sure what to do. here I need to isolate hostname
  for /f "tokens=2" %%b in ('nslookup %SourceDir%^|find /i "Address"') do set ser_ip=%%b
  REM here I need to replace my_server with %ser_ip%     
)

在这段代码中,我试图用网络路径中的IP地址替换主机名。

    我需要在set sourceHost= REM not sure what to do. here I need to isolate hostname行中
  1. 将主机名与路径
  2. 隔离开来 REM here I need to replace my_server with %ser_ip%行中的
  3. 需要用检索到的IP地址替换主机名
  4. 如果nslookup ip地址为10.12.13.14,则上次结果应为\\10.12.13.14\path 请帮我这两行。谢谢!

2 个答案:

答案 0 :(得分:1)

我会选择ping而不是nslookup。如果存在IPv6地址,则更难以解析,并且ping具有-4选项 ip很容易提取,因为它用方括号括起来。:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
set "SourceDir=\\my_server\path"
if "%SourceDir:~0,2%"=="\\" (
  for /f "delims=\" %%H in ( "%SourceDir%"
  ) Do for /f "tokens=2delims=[]" %%b in ('ping -n 1 -4 %%H^|find "["'
  ) do Set "SourceDir=!SourceDir:%%H=%%b!"
)
Echo %SourceDir%

答案 1 :(得分:1)

这个怎么样(假设你想坚持nslookup):

set "SourceDir=\\my_server\path"

if "%SourceDir:~0,2%"=="\\" (
  rem // Extract server name and splif off remaining path:
  for /F "tokens=1* delims=\" %%a in ("%SourceDir%") do set "sourceHost=%%a" & set "sourceShare=%%b"
  for /F "tokens=2" %%b in ('nslookup %SourceDir%^|find /I "Address"') do set "ser_ip=%%b"
  rem // Assemble new path by IP and former remaining path:
  echo "\\%ser_ip%\%sourceShare%"
)