稳健而有效的方法从 Windows 执行基于 shebang-line 的 shell 脚本 is via wsl.exe -e
wsl -e ./simple_script.sh # !! ./ is required
Note:
As for 你尝试过什么:
$simple_script = Get-Content ./simple_script.sh
wsl bash -c $simple_script
主要问题是Get-Content https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-content默认情况下返回一个array行,并尝试使用该数组作为参数外部程序例如wsl
导致数组的元素被传递作为单独的论点.
The 立即修复是使用-Raw
switch,这使得Get-Content
将文件内容返回为单行、多行字符串.
然而,由于一个非常不幸的、长期存在的错误,PowerShell - 最高 v7.2.x - 需要manual \
-escaping of 嵌入式"
人物在传递给外部程序的参数中.
- See 这个答案 https://stackoverflow.com/a/59036879/45375了解详情。
所以:
# Using -Raw, read the file in full, as a single, multi-line string.
$simple_script = Get-Content -Raw ./simple_script.sh
# !! The \-escaping is needed up to PowerShell 7.2.x
wsl bash -c ($simple_script -replace '"', '\"')
请注意,虽然它是试图通过提供脚本文本来绕过转义的需要通过管道 (stdin), this does not从 PowerShell 7.3.3 开始,按预期工作:
# !! Tempting, but does NOT work.
Get-Content -Raw ./simple_script.sh | wsl -e bash
这不起作用的原因是PowerShell 总是附加一个Windows格式换行符(CRLF)到通过管道发送到外部程序的内容,Bash 无法识别。
- 这种有问题的行为正在讨论中GitHub 问题 #13579 https://github.com/PowerShell/PowerShell/issues/13579.