Linux 的 Powershell:将命令与管道符号结合使用不起作用

Powershell for Linux: Combining commands with pipe sign doesn't work

有什么方法可以在 Powershell 中为 Linux 连接命令?

这就是我想要的 运行:

pwsh -Command Invoke-ScriptAnalyzer -Path . | ConvertTo-Json | Out-File -FilePath "/home/administrator/scripts/test.json"

因此,运行 Invoke-ScriptAnalyzer,将结果转换为Json并将结果保存到test.json。

它在 | 之后不识别任何内容符号:

./test.sh: line 1: ConvertTo-Json: command not found

./test.sh: line 1: Out-File: command not found

我需要它进入 bash 脚本,因此需要使用 -Command 选项启动 pwsh。

有什么想法吗?

谢谢

正如所写,您的 | 符号由您的 Linux shell 解释 (例如 bash),不是 PowerShell。

有两种解决方案:

  • 最好引用整个 -Command 参数(POSIX 兼容 shell 中的 '...' 字符串,例如 bash 使用字符串的内容 逐字记录):
pwsh -Command 'Invoke-ScriptAnalyzer -Path . | ConvertTo-Json | Out-File -FilePath "/home/administrator/scripts/test.json"'

  • 或者,单独 \- 逐字转义所有 Linux-shell 元字符通过,例如 \|\" 在这种情况下:
pwsh -Command Invoke-ScriptAnalyzer -Path . \| ConvertTo-Json \| Out-File -FilePath \"/home/administrator/scripts/test.json\"

注意:在这种情况下,pwsh-Command 之后接收 多个 个参数。但是,PowerShell 在将结果解释为 PowerShell 代码之前只是 加入它们
这不同于 POSIX-compatible shells 的命令行处理,它将 first post--c 参数解释为一个隐式的临时脚本附加参数作为逐字参数传递给该脚本,像往常一样访问 , ...