如何使用 PowerShell 更新 Windows 主机文件条目?


假设你要更新 host 文件的特定条目,我们的本地计算机中有以下 host 文件。

示例

Get-Content $env:windir\system32\drivers\etc\hosts

输出

# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost
8.8.8.8   Google.com

我们需要将 google.com 条目更新为 IP 地址 4.4.4.4。

示例

$hostfile = "$env:windir\system32\drivers\etc\hosts"
$file = Get-Content $hostfile
$newfile = $file -replace "8.8.8.8   Google.com","4.4.4.4   Google.com"
Set-Content -Value $newfile -Path $hostfile -Force

再次检查 host 文件后,会显示一个新条目。

若要在远程计算机上更新 host 文件,只需更改$hostfile变量位置,其余内容保持不变。

$hostfile = "\RemoteServer\C$\Windows\system32\drivers\etc\hosts"

更新于:2021-03-18

3K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.