这个问题与这个问题有关:Powershell: how to execute command for a path containing Unicode characters?
我有一个 Node.js 应用程序,它使用 Powershell 5.1 生成一个子进程,然后重新使用它来运行不同的命令,因为它比生成单独的进程更快。
问题
问题是,包含 Unicode 字符的命令会静默失败。
代码
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");
编辑#1在将命令发送到 Powershell 然后将其转换为 System.Char 之前,我尝试在 Node.js 端对 UTF-8 的路径进行编码:
const path = 'E:/test $([char]0x1f4da).txt'
const command = `Get-Acl $(${path}).access`
testProcess.stdin.write(`${command}\n`)
但我不知道如何正确地做到这一点。好像我没有将它编码为正确的格式。这也不是一个真正合适的解决方案,我只是手动将表情符号编码为 utf。我可能需要将整个路径转换为 UTF-16 或其他东西以确保其中没有不受支持的字符:"E:/test 📚.txt".split("").reduce((hex,c) => hex += c.charCodeAt(0).toString(16).padStart(4,"0"),"")
不确定它是否会起作用
最佳答案
尝试以下操作:
let childProcess = require('child_process')
let testProcess = childProcess.spawn(
'chcp 65001 >NUL & powershell.exe -NonInteractive -NoProfile -Command -',
{ shell: true }
)
testProcess.stdout.on('data', (data) => {
console.log(data.toString())
})
testProcess.stdout.on('error', (error) => {
console.log(error)
})
testProcess.stdin.write("Get-Item '📚.txt'\n");
powershell.exe
, Windows PowerShell CLI也不异常(exception),因此为了使其将其标准输入输入解释为 UTF-8,OEM 代码页必须显式设置为 UTF-8 代码页,65001
, 在 powershell.exe
之前启动。{ shell : true }
用于确保 powershell.exe
通过 cmd.exe
启动,Windows 上的默认 shell,允许执行 chcp 65001
首先,它执行到 UTF-8 代码页的切换。-NonInteractive
用于告诉 PowerShell 在 session 中不需要用户交互,这会显着阻止加载 PSReadLine
用于命令行编辑的模块,这可能会导致 BMP 之外的 Unicode 字符出现问题,即代码点高于 0xFFFF
的字符(如 📚
),需要两个 [char]
.NET 中的实例。-NoProfile
阻止加载(点源)PowerShell配置文件,因为它们(a)通常只在交互式 session 中需要,并且(b)它们的加载不仅会减慢速度,而且会产生副作用。-Command -
告诉 PowerShell 从标准输入读取命令;虽然省略这个参数有点类似,但它相当于 -File -
,它表现出伪交互行为。-Command -
和(暗示)-File -
表现出意想不到的行为,如 GitHub issue #3223 中所述和 GitHub issue #15331 关于Node.js + Powershell : how to encode Unicode characters when using stdin. 写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67578079/