node.js - 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']
)
解决方案
通过使用stdin输入向powershell.exe
Windows PowerShell CLI提供命令,您隐含地依赖系统的活动OEM代码页,因为 PowerShell CLI 使用它来解码通过 stdin 接收的输入。
除非您已明确选择允许将旧代码页(ANSI 和 OEM)设置为 UTF-8 的仍处于测试阶段的 Windows 10 功能,否则OEM 代码页是一种固定的单字节编码,限制为 256 个字符,缺少支持大多数 Unicode 字符,例如美国英语系统上的代码页 437 。
此外,通过 stdin 提供命令(可以用 显式请求
-File -
)意外地使 PowerShell 表现出伪交互行为,这会干扰命令输出。有关此问题行为的讨论,请参阅GitHub 问题 #3223和GitHub 问题 #15331。
相比之下,通过-c
( -Command
) CLI参数传递命令完全支持 Unicode,而与活动的 OEM 代码页无关,因此它是绕过原始问题的简单替代方案;从您自己的更新中借用您的问题:
childProcess.spawn(
'powershell',
['-NoProfile', '-Command', '(Get-Acl "E:/test .txt").access']
)
请注意,我添加-NoProfile
是为了使调用更可预测/加快速度,因为此选项会抑制通常仅与交互使用相关的配置文件的加载。
推荐阅读
- bash - 需要帮助将源目录添加到 bash 脚本
- c++ - 既然我们有内联变量,还有用 extern const 吗?
- c++ - 我在 OpenGL 中显示图像时遇到问题
- generics - Dagger MutableLiveData 标识符
- sql - 将数组放入 WHERE IN 子句 Ruby on Rails
- sql - 如何获得每个岛屿的第一排和最后一排?
- javascript - 如何在数组Javascript上查找字符串的索引
- javascript - 当我修改 img src 时,jsPDF 不打印 img
- python - 如何在python中使用地理编码器获取邮政编码,提供地理坐标
- express - 将异步等待与猫鼬和快递一起使用