explorer.exe 在 WSL 中以编程方式 运行 时无法打开正确的文件夹

explorer.exe doesn't open correct folder when ran programmatically inside WSL

我正在尝试从 WSL Ubuntu 20.04 中的 Node.js 脚本 运行ning 打开 explorer.exe。我遇到的问题是 explorer.exe 从不打开我想要打开的文件夹。它打开了我的 Windows 用户的 Documents 文件夹,而不是 WSL 用户的主目录。我应该怎么做才能explorer.exe打开我想要的文件夹?

这是我尝试过的方法:

脚本首先定义了一个函数execShellCommand,它承诺exec。然后自执行函数首先将process.env.HOME 转换为Windows 路径与wslpath。然后它以转换后的路径作为参数执行explorer.exe

#!/usr/bin/node

const execShellCommand = async cmd => {
  const exec = require('child_process').exec
  return new Promise((resolve, reject) => {
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        console.warn(error)
      }
      resolve(stderr ? stderr : stdout)
    })
  })
}

;(async () => {
  const path = await execShellCommand(`wslpath -w "${process.env.HOME}"`)
  console.log({ path })
  await execShellCommand(`explorer.exe ${path}`)
})()

我在 WSL 中 运行 我的脚本时得到的输出

$ ./script.js 
{ path: '\\wsl$\Ubuntu-20.04\home\user\n' }
Error: Command failed: explorer.exe \wsl$\Ubuntu-20.04\home\user


    at ChildProcess.exithandler (child_process.js:308:12)
    at ChildProcess.emit (events.js:315:20)
    at maybeClose (internal/child_process.js:1048:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5) {
  killed: false,
  code: 1,
  signal: null,
  cmd: 'explorer.exe \\wsl$\Ubuntu-20.04\home\user\n'
}

explorer.exe 执行 运行 而不管输出中显示的错误。奇怪的是,如果我 运行 我的脚本尝试直接在 WSL 终端 运行 (explorer.exe \\wsl$\Ubuntu-20.04\home\user\n) explorer.exe 中打开我想要的文件夹。修剪路径末尾的新行没有帮助。

我认为您必须对 wslpath 生成的反斜杠进行一些额外的转义。下面的代码对我有用,意思是 它在 Windows Explorer.

中打开正确的目录

注意:它仍然会抛出您提到的错误,我认为这是由于节点退出的方式而不是 w/the 执行 explorer.exe 的任何错误;我无论如何都不是节点专家。

#!/usr/bin/node

const execShellCommand = async cmd => {
          const exec = require('child_process').exec
          return new Promise((resolve, reject) => {
                      exec(cmd, (error, stdout, stderr) => {
                                    if (error) {
                                                    console.warn(error)
                                                  }
                                    resolve(stderr ? stderr : stdout)
                                  })
                    })
}

;(async () => {
          let path = await execShellCommand(`wslpath -w "${process.env.HOME}"`)
          console.log("before", {path});
          path = path.replace(/\/g,"\\");
          console.log("after", {path});
          await execShellCommand(`explorer.exe ${path}`)

})()

比替换反斜杠更干净,我认为这将通过将 $HOME 变量直接解析到您的命令行中来为您工作:

await execShellCommand(`explorer.exe "$(wslpath -w $HOME)"`);