首页 > 解决方案 > Powershell:如何为包含 Unicode 字符的路径执行命令?

问题描述

我正在尝试在 Powershell 5.1 中执行命令,但是当路径包含 Unicode 字符时它会失败。

例如:

(Get-Acl 'E:/test .txt').access

我正在从 Node.js 运行命令:

let childProcess = require('child_process')
let testProcess = childProcess.spawn('powershell', [])
testProcess.stdin.setEncoding('utf-8')

testProcess.stdout.on('data', (data) => {
  console.log(data.toString())
})

testProcess.stdout.on('error', (error) => {
  console.log(error)
})

// This path is working, I get command output in the console:
// testProcess.stdin.write("(Get-Acl 'E:/test.txt').access\n");

// This path is not working. I get nothing in the console
testProcess.stdin.write("(Get-Acl 'E:/test .txt').access\n");

我无法使用 Powershell 7,因为我正在制作一个在预安装的 Powershell 上运行命令的 Node.js 应用程序

更新

这种方法似乎有效:

childProcess.spawn(
  'powershell', 
  ['-Command', '(Get-Acl "E:/test .txt").access']
)

标签: node.jspowershellshellcommand-linecommand-line-interface

解决方案


通过使用stdin输入向powershell.exeWindows PowerShell CLI提供命令,您隐含地依赖系统的活动OEM代码页,因为 PowerShell CLI 使用它来解码通过 stdin 接收的输入。

相比之下,通过-c( -Command) CLI参数传递命令完全支持 Unicode,而与活动的 OEM 代码页无关,因此它是绕过原始问题的简单替代方案;从您自己的更新中借用您的问题:

childProcess.spawn(
  'powershell', 
  ['-NoProfile', '-Command', '(Get-Acl "E:/test .txt").access']
)

请注意,我添加-NoProfile是为了使调用更可预测/加快速度,因为此选项会抑制通常仅与交互使用相关的配置文件的加载。


推荐阅读