【问题标题】:Powershell: how to execute command for a path containing Unicode characters?Powershell:如何为包含 Unicode 字符的路径执行命令?
【发布时间】:2021-05-18 09:39:32
【问题描述】:

我正在尝试在 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']
)

【问题讨论】:

  • 确保包含表情符号字符文字的脚本是 Unicode 编码 (UTF16LE),否则 Windows PowerShell 将阻塞 UTF-8 表示。
  • @MathiasR.Jessen,虽然将 PowerShell 脚本保存为 UTF-16LE 确实有效,但 UTF-8 with BOM 也是如此,而且由于脚本通常大多包含 ASCII 范围的字符,就文件大小而言,后者更可取。
  • 如何使用参数设置编码?我尝试将-encoding utf8 和-encoding UTF16LE 添加到命令中,但它也不起作用
  • @AlekseyHoffman -Encoding Unicode
  • @mklement0 感谢您的解决方案。使用-Command 将命令作为参数数组传递似乎有效:childProcess.spawn('powershell', ['-Command', '(Get-Acl "E:/test ????.txt").access']) 我在控制台中得到命令输出

标签: node.js powershell shell command-line command-line-interface


【解决方案1】:

通过使用stdin 输入向powershell.exe、Windows PowerShell CLI 提供您的命令,您隐含地依赖于系统的活动 OEM 代码页,因为这是 PowerShell CLI 用来解码通过标准输入接收到的输入。

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

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

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

【讨论】:

  • 感谢您的解释。你认为有办法让它与stdin.write(我最初的方法)一起工作吗?我可以在发送命令之前使用 Node.js 对文件路径进行编码,还是在处理命令之前使用 powershell 本身对文件路径进行编码?
  • @AlekseyHoffman,我不知道您是否看过我的更新,说明 stdin 命令输入显示的伪交互行为。您可以在某种程度上通过-Command - 从标准输入读取来缓解这种情况,但问题是:为什么需要标准输入输入?
  • @AlekseyHoffman,如果您确实需要标准输入输入 - 这样您就可以随着时间的推移将多个命令作为一种伪 REPL 提供给单个 powershell.exe 进程 - 可以我建议您创建一个专门针对该问题的新问题?
  • 我正在使用 stdin.write 因为它对我的用例来说更快。 Node 产生一个子进程大约需要 500 毫秒。所以我想我可以在应用加载期间创建一个进程,然后重新使用它
  • 感谢您的其他建议。 -noProfile 对第二种方法有意义。关于 unicode 转换,我发现了一件有趣的事情,我注意到当我手动将这个命令:(Get-Acl "E:/test ?.txt").access 复制粘贴到 powershell 中时,它将 unicode 字符转换为 ?? 并且工作得很好。所以我想知道,有没有办法利用它来使用 powershell 功能预处理路径?另外我不确定“通过 -Command 从标准输入读取来缓解这种情况”是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 2014-09-01
  • 2018-11-02
  • 2013-04-06
  • 1970-01-01
相关资源
最近更新 更多