【发布时间】: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