首页 > 解决方案 > 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,我正在寻找的解决方案将返回实际的默认文本编辑器文件位置,以便它可以用来打开如上所示的文件。

标签: powershellregistry

解决方案


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,现在你就得到了与文本文件关联的编辑器的真实路径。

要阅读有关该主题的更多信息,这篇博客文章非常好,并详细介绍了关联的工作原理。


推荐阅读