Powershell 相当于 "Open with Code" Windows shell 扩展?

Powershell equivalent of "Open with Code" Windows shell extension?

当我在 Windows 资源管理器中选择“使用代码打开”shell 扩展时,它会在现有的 VS 代码 window 中打开文件。我想在我的构建过程中从 Powershell 脚本执行相同的操作,以将一些输出日志加载到 VS Code 中。

刚刚执行:

& "C:\Program Files\Microsoft VS Code\Code.exe" .\install.log

总是打开一个新实例

我查看了有关创建新注册表项的注册表更改 here but it does not behave the way the shell extension behaves - it always just opens a new Code instance. Also, despite additional comments here,这实际上不是 shell 扩展的工作方式。

这是找到现有的运行代码进程并发送消息打开文件的情况吗?

不幸的是,使用:

Get-Process | Where-Object { $_.ProcessName -eq "Code" }

打开一个代码 window,显示八个代码进程...

或者现有的 shell 扩展代码可能已经在某处可用,所以我可以看到它如何让现有的代码实例打开文件?

问题是因为 VS Code 随着时间的推移更改了安装位置

解决方案:只要您实际调用与现有 vscode 进程相同的二进制文件,它将在现有 window 中打开(基于当前操作)。由于供应商随时间更改安装路径,验证您没有多个二进制文件非常重要。这也会影响上面链接中提到的注册表修复。

其实这个...

[Get-Process | Where-Object { $_.ProcessName -eq "Code" }] 

...即使看起来像您打开了一个 Code.exe window 实际上它也将始终是 2 个或更多,具体取决于您对 VSCode 配置的内容和方式.例如,在我的开发箱上执行此操作会返回 9...

Get-Process | 
Where-Object { $_.ProcessName -eq "Code" } | 
Select-Object -Property ID, SessionId, Path, PriorityClass

<#
   Id SessionId Path                                                                 PriorityClass
   -- --------- ----                                                                 -------------
 1200         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
 2520         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
 5168         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
 6292         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe   AboveNormal
10856         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
13556         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
16920         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
19528         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
20424         2 C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code\Code.exe        Normal
#>

...这是发布时。

另外,你为什么要这样调用 VSCode?

& "C:\Program Files\Microsoft VS Code\Code.exe" .\install.log

在安装时,它会添加到您的用户路径(除非您在安装时更改了它)...

C:\Users\postanote\AppData\Local\Programs\Microsoft VS Code

...所以你只需要这样做...

code D:\Temp\abc.txt

...从 PowerShell 控制台主机、ISE、VScode 等调用它时,它将加载到您正在使用的当前实例中。

我每天都这样做。在 VSCode 出现之前,在 ISE 中,您调用 psEdit 来做同样的事情。

psEdit -filenames D:\Temp\abc.txt

如果您已经在 VScode,只需按 F1,然后退格,然后输入文件的完整路径。不需要其他代码启动。