更新主机文件以根据主机名更新最后一个条目

时间:2017-09-08 12:38:20

标签: windows powershell hostname hosts

出于某种原因,我们的一个客户在连接到我们的ftp时遇到很多问题,主要原因是他无法解析我们的主机名(通过IP没问题)

我一直在环顾四周,发现这段代码在主机文件的底部添加了一行(但它不起作用,只是完整地输出主机文件)

有人可以解释我如何改变这个吗?它完美地获取IP,只需删除主机文件上的非注释行或删除最后一个IP

$targethost="HOSTNAME"
$dnsserver="8.8.8.8"
$pattern = '^*' + $targethost + '.*$'
$file = "$($env:SystemRoot)\System32\drivers\etc\hosts"
$ip = Resolve-DnsName -Name $targethost -Type A -DnsOnly -Server $dnsserver
$hosts = Get-Content -Path $file

$hosts = $hosts | Foreach {
  if ($_ -match $pattern) 
  {
      $ip.IpAddress + "   HOSTNAME "
  } 
  else 
  {
    # Keep current line
    $_
  }
}

#Uncomment this line to just view the output, no harm is done to the hosts file.
$hosts


# Uncomment this line to actually write the hosts file. Elevated privileges required.
#$hosts | Out-File $file -enc ASCII

2 个答案:

答案 0 :(得分:0)

尝试

$hosts | Out-File -Encoding Ascii -append $file 

$hosts | Add-Content $file #(ASCII by default)

答案 1 :(得分:0)

一个笨拙的,但它有效

Clear-Content c:\windows\System32\drivers\etc\hosts
Set-Content -Path c:\windows\System32\drivers\etc\hosts -Value "Hello, World"
$targethost="HOSTNAME"
$dnsserver="8.8.8.8"
$pattern = '^*' + $targethost + '.*$'
$file = "$($env:SystemRoot)\System32\drivers\etc\hosts"
$ip = Resolve-DnsName -Name $targethost -Type A -DnsOnly -Server $dnsserver
$hosts = Get-Content -Path $file

$hosts = $hosts | Foreach {
  if ($_ -match $pattern) 
  {
      # Keep current line
    $_

  } 
  else 
  {
   $ip.IpAddress + "   HOSTNAME "
  }
}

#Uncomment this line to just view the output, no harm is done to the hosts file.
$hosts


# Uncomment this line to actually write the hosts file. Elevated privileges required.
$hosts | Out-File $file -enc ASCII