出于某种原因,我们的一个客户在连接到我们的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
答案 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