powershell - PowerShell:在默认 txt 编辑器中打开文件
问题描述
我试图找到一种方法来使用 PowerShell 在默认文本编辑器中打开非 txt 文件(在本例中为 hosts 文件)。
看到这个 Reddit 帖子后,我取得了一些进展,但$txt_editor
结果总是返回 Notepad.exe,即使 Notepad++ 是我的 txt 文件的默认编辑器。
$hosts_file = "$env:windir\System32\drivers\etc\hosts"
$txt_editor = ((Get-ItemProperty -Path 'Registry::HKEY_CLASSES_ROOT\txtfile\shell\open\command').'(Default)').trimend(" %1")
Start-Process -FilePath $txt_editor -Verb Runas -ArgumentList $hosts_file
这也会返回 Notepad.exe:
(Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\OpenWithList' -Name a).a
如果我在注册表编辑器中查看上述位置,我确实看到 Notepad++ 与键一起列出d
,但我不知道如何仅通过查看注册表键来判断默认文本编辑器是什么,因为我在中看到的两个解决方案Reddit 不工作。
我使用的是 Windows 10,我正在寻找的解决方案将返回实际的默认文本编辑器文件位置,以便它可以用来打开如上所示的文件。
解决方案
Start 命令(它是 的别名Start-Process
)将在其默认编辑器中启动任何文件。
start .\MyCoolbmp.bmp
#Opens in MSPaint
start .\SomeNotes.txt
#Opens in Notepad
start .\SomeJason.json
#Opens in Visual Studio, go ahead and grab a coffee...
如果我不得不猜测您的为什么不起作用,那是您提供的注册表项是用于系统的注册表项,而用户的默认编辑器从 Windows 7 及更高版本存储在 HKEY_CURRENT_USER 配置单元中,而不是在此路径Windows\CurrentVersion\Explorer\FileExts\.txt\UserChoice'
.
以下是相关值:
$txtKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txt\UserChoice"
Get-ItemProperty -Path $txtKey | tee-object -variable txtPath
Hash : noCJnt8yX5Y=
ProgId : VSCode.txt
这与在 HKCR:\Applications 中找到的信息相关联,可以在其中找到真实路径。
get-itemproperty Registry::\HKEY_CLASSES_ROOT\$($txtPath.ProgId)\shell\open\command
(default) : "C:\Program Files\Microsoft VS Code\Code.exe" "%1"
#...
如果你抓住那个 (Default) value,现在你就得到了与文本文件关联的编辑器的真实路径。
要阅读有关该主题的更多信息,这篇博客文章非常好,并详细介绍了关联的工作原理。
推荐阅读
- javascript - 如何格式化此关联获取续集
- reactjs - 为文件加载添加自定义按钮
- javascript - 为什么使用 $(document).height() 每次点击都会增加背景?
- c++ - RPi Pico 在 IRQ 中断调用上冻结
- javascript - 赛普拉斯 - 遍历数组
- vue.js - 如何在 Vue.js 中绑定 API 响应中的选项数据?
- javascript - 缩短具有不同 id 的重复动作
- sql - BigQuery:左半连接问题
- javascript - 渲染导致奇怪工件的深层嵌套有状态组件列表 - Angular
- excel - 如果通过“完成”满足值,则显示最旧日期