重置目标是将全网终端hosts文件恢复为仅含“127.0.0.1 localhost”等默认条目的初始化状态;须以管理员权限执行,操作前备份原文件用于审计,生产环境应在非高峰时段实施,并通过GPP、Intune或PsExec批量部署经兼容性验证的PowerShell脚本。
明确重置目标与安全前提
批量重置全网终端的 hosts 文件 到初始化状态,本质是用统一、干净的内容(如仅保留 127.0.0.1 localhost)覆盖所有客户端的 c:\windows\system32\drivers\etc\hosts。但必须注意:此操作需管理员权限,且不可逆;若 hosts 被恶意篡改过,重置前建议先采集原始内容用于审计。生产环境务必在非业务高峰期执行,并提前验证脚本在典型终端上的兼容性(如 windows 10/11、不同 uac 级别、防病毒软件拦截行为)。
核心 PowerShell 脚本(本地单机版)
以下脚本可安全替换本地 hosts 文件为最小初始化内容(保留 BOM 兼容性,绕过系统只读属性):
$hostsPath = "$env:windir\System32\drivers\etc\hosts"
$initContent = @'
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
<p>127.0.0.1 localhost
::1 localhost
'@</p><h1>移除只读属性(避免写入失败)</h1><p>if ((Get-Item $hostsPath).IsReadOnly) {
Set-ItemProperty -Path $hostsPath -Name IsReadOnly -Value $false
}</p><h1>以 UTF-8 无 BOM 写入(部分旧版记事本依赖 BOM,此处用带 BOM 的 UTF8)</h1><h1>可选:刷新 DNS 缓存</h1><p>ipconfig /flushdns | Out-Null
扩展为全网批量执行(推荐方式)
不建议直接远程调用 Invoke-Command 对数百台终端并发执行(易触发 WinRM 限流或超时)。更稳妥的做法是:
-
通过组策略首选项(GPP)部署:新建“文件”首选项,源文件为已准备好的干净 hosts,目标路径设为
%SystemRoot%\System32\drivers\etc\hosts,勾选“替换”,作用域限定于目标 OU;GPP 自动处理权限和重启后生效 - 结合 SCCM/Intune 推送脚本:将上述脚本封装为 .ps1,设置执行策略为 Bypass,以“系统上下文”运行;Intune 中选择“设备脚本”,部署前启用“运行脚本即使用户未登录”
-
使用 PsExec 辅助(临时应急):在域控或管理机上运行(需本地管理员凭据):
psexec @targetlist.txt -u DOMAIN\Admin -p Password -h -n 10 powershell.exe -ExecutionPolicy Bypass -File reset-hosts.ps1
其中targetlist.txt每行一个主机名或 IP,-h提升到高完整性级别,-n 10设置超时
验证与回滚机制
重置后必须快速验证效果并留有退路:
- 验证:在目标终端运行
Get-Content C:\Windows\System32\drivers\etc\hosts | Select-Object -First 5,确认输出含127.0.0.1 localhost且无异常条目 - 回滚:脚本执行前自动备份原文件(加时间戳),例如:
Copy-Item $hostsPath "$hostsPath.backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')" - 网络级兜底:若因 hosts 清空导致关键内部域名无法解析,可临时在 DNS 服务器添加对应 A 记录,避免业务中断

















