You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在WSL2中如何让PowerShell命令的输出打印到标准输出?

在WSL2中执行PowerShell命令并输出结果的解决方法

你遇到的问题是在WSL2的bash环境中执行pwsh.exe -Command时,输入的命令被原样返回而非执行,这是因为WSL的shell对命令参数的解析和PowerShell的语法存在冲突。以下是可行的解决方式:

基础解决写法

直接用引号包裹PowerShell命令内容,避免WSL shell解析命令中的特殊符号:

# 执行单条命令
pwsh.exe -Command "Get-Date"

# 输出字符串
pwsh.exe -Command "Write-Output 'hello'"

多命令或带变量的场景

如果需要执行多条命令或使用变量,注意在bash中对特殊字符的转义:

  • 用双引号包裹整个命令时,PowerShell中的$需要在bash中转义为\$:
pwsh.exe -Command "\$message = 'Hello from PowerShell'; Write-Output \$message"
  • 或者用单引号包裹整个命令字符串,这样bash不会解析内部的$符号,直接传递给PowerShell执行:
pwsh.exe -Command '$message = "Hello from PowerShell"; Write-Output $message'

问题原因说明

之前的写法失效是因为:

  • {Get-Date}中的{}会被bash当作大括号扩展语法处理,而非传递给PowerShell作为命令块
  • 使用'{Write-Output "hello"}'时,PowerShell接收后会将整个单引号包裹的内容当作字符串输出,而非解析执行命令

内容的提问来源于stack exchange,提问作者Mattias Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 10:45:33