You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell Cmdlet或Windows运行对话框打开Windows系统host文件?

打开Windows Hosts文件的PowerShell方案

直接可用的命令

不管是在运行对话框还是PowerShell里,都可以用以下命令快速打开hosts文件:

  • 运行对话框(Win+R)输入:notepad %windir%\system32\drivers\etc\hosts
  • PowerShell中输入:notepad $env:windir\system32\drivers\etc\hosts

注意:如果需要修改并保存hosts文件,必须以管理员身份启动记事本或PowerShell,否则保存操作会失败。

自定义PowerShell Cmdlet风格函数

如果你希望有一个专用的Cmdlet来完成这个操作,可以自己编写一个PowerShell函数,用法和原生Cmdlet一致:

function Open-HostsFile {
    [CmdletBinding()]
    param(
        # 指定用来打开hosts文件的编辑器,默认用记事本
        [string]$Editor = "notepad"
    )
    
    $hostsPath = Join-Path -Path $env:windir -ChildPath "system32\drivers\etc\hosts"
    
    if (-not (Test-Path -Path $hostsPath)) {
        Write-Error "未找到hosts文件,路径:$hostsPath"
        return
    }
    
    try {
        & $Editor $hostsPath
        Write-Verbose "已通过$Editor打开hosts文件"
    }
    catch {
        Write-Error "启动编辑器失败:$_"
    }
}

使用说明

  • 直接调用:Open-HostsFile(用记事本打开)
  • 指定编辑器:Open-HostsFile -Editor "code"(用VS Code打开,需确保编辑器已加入系统PATH)
  • 若要永久使用这个函数,将代码添加到你的PowerShell配置文件中(运行notepad $PROFILE打开配置文件,粘贴代码后保存,下次启动PowerShell即可直接调用)

内容的提问来源于stack exchange,提问作者Dev Anand Sadasivam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:42:08