powershell是windows下最实用的本地hosts自动化管理工具,需管理员权限运行,支持覆盖、追加、删除操作,并可脚本化自动更新与定时维护。
powershell 是 windows 系统下最实用的本地 hosts 自动化管理工具。它能绕过图形界面权限限制,精准控制写入内容、编码格式和执行时机,避免手动编辑常见的“保存失败”“不生效”问题。
安全前提:必须以管理员权限运行
HOSTS 文件位于 C:\Windows\System32\drivers\etc\hosts,受系统保护。任何 PowerShell 操作都需在“Windows Terminal(管理员)”或“PowerShell(管理员)”中执行,否则会提示“拒绝访问”或静默失败。
- 验证权限:运行
Get-Process -Id $PID | Select-Object ElevationToken,输出High表示已提权 - 常见误区:仅用普通 PowerShell 执行
notepad hosts,看似打开文件,但保存时仍会失败 - 推荐启动方式:右键开始菜单 → “Windows Terminal(管理员)”,或快捷键
Win+X→A
基础操作:覆盖、追加与清理
不用记事本,也能完成全部编辑动作。PowerShell 提供三类核心命令,对应不同场景:
-
完全替换为初始化内容(如重置环境):
$content = "127.0.0.1 localhost`r`n::1 localhost"; Set-Content -Path "$env:windir\System32\drivers\etc\hosts" -Value $content -Encoding UTF8 -
追加单行记录(如临时映射开发域名):
Add-Content -Path "$env:windir\System32\drivers\etc\hosts" -Value "`r`n192.168.1.50 api.dev.local"(开头换行防粘连) -
删除指定行段(如清除旧的 GitHub520 区块):
$lines = Get-Content "$env:windir\System32\drivers\etc\hosts"; $newLines = $lines | Where-Object { $_ -notmatch "# GitHub520 Host Start|GitHub520 Host End" }; $newLines | Set-Content "$env:windir\System32\drivers\etc\hosts" -Encoding UTF8
实战脚本:自动更新 GitHub 加速条目
以 GitHub520 项目为例,脚本需完成“定位旧区块→清除→拉取新内容→写入→刷新 DNS”全流程,避免重复追加:
- 从
https://raw.hellogithub.com/hosts获取最新条目 - 用
# GitHub520 Host Start和# GitHub520 Host End作为标记边界,精准替换区间 - 写入前移除 hosts 文件只读属性:
(Get-Item "$env:windir\System32\drivers\etc\hosts").IsReadOnly = $false - 末尾强制执行:
ipconfig /flushdns | Out-Null,确保修改即时生效
长期维护:注册计划任务自动执行
手动运行适合一次性操作;生产或开发环境中,建议部署定时任务,每周自动同步最新 hosts 规则:
- 保存脚本为
C:\Scripts\Update-GitHubHosts.ps1(注意启用执行策略:Set-ExecutionPolicy RemoteSigned -Scope CurrentUser) - 用
Register-ScheduledTask创建每日凌晨 2 点执行的任务,触发器设为“按计划”+“不管用户是否登录” - 任务操作配置为:
powershell.exe -ExecutionPolicy Bypass -File "C:\Scripts\Update-GitHubHosts.ps1" - 可配合日志记录:
Out-File -FilePath "C:\Logs\HostsUpdate.log" -Append -InputObject "$(Get-Date): Success"











