PowerShell:如何对包含Unicode字符的路径执行命令? [英] Powershell: how to execute command for a path containing Unicode characters?
问题描述
我尝试在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
");
// This path is not working. I get nothing in the console
testProcess.stdin.write("(Get-Acl 'E:/test 📚.txt').access
");
我无法使用Powershell 7,因为我正在制作在预装的Powershell上运行命令的Node.js应用程序
更新
此方法似乎有效:
childProcess.spawn(
'powershell',
['-Command', '(Get-Acl "E:/test 📚.txt").access']
)
推荐答案
使用stdin输入将您的命令提供给Windows PowerShell CLIWindows PowerShell CLI,您隐式依赖于系统的活动OEM代码页,因为PowerShell CLI使用该代码页解码通过stdin接收的输入。
除非您已明确选择still-in-beta Windows 10 feature that allows setting both legacy code pages - ANSI and OEM - to UTF-8,否则OEM代码页是固定的单字节编码,限制为256个字符,不支持大多数Unicode字符,如Code page 437在美英系统上。
此外,通过stdin提供命令(可以使用
-File -
显式请求)意外导致PowerShell显示伪交互行为,这会干扰命令输出。有关此问题行为的讨论,请参阅GitHub issue #3223和GitHub issue #15331。
相比之下,通过-c
(-Command
)CLI参数传递命令完全支持Unicode,而不考虑活动的OEM代码页,因此这是一个绕过原始问题的简单替代方案;借用您自己的更新来解决您的问题:
childProcess.spawn(
'powershell',
['-NoProfile', '-Command', '(Get-Acl "E:/test 📚.txt").access']
)
请注意,我添加了-NoProfile
以使调用更可预测/加快,因为此选项禁止加载通常仅与交互式使用相关的配置文件。
这篇关于PowerShell:如何对包含Unicode字符的路径执行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!