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

PowerShell中一行执行WSL命令失败,提示‘cut未被识别’求解决

问题描述

想要编写一个PowerShell函数,调用WSL执行以下Bash命令:

HOSTIP=`cat /etc/resolv.conf | grep nameserver | cut -b 12-`
cd /tmp; mkfifo pip; nc -l -p 12345 < pip | nc ${HOSTIP} 12345 > pip

尝试的PowerShell命令:

wsl -e sh -c "HOSTIP=\$(cat /etc/resolv.conf | grep nameserver | cut -b 12-); cd /tmp; mkfifo pip; nc -l -p 12345 < pip | nc \${HOSTIP} 12345 > pip"

执行时报错 cut is not recognised,询问这是否是PowerShell中执行WSL命令的正确方式。

问题原因与解决方法

报错的核心原因是PowerShell解析了命令中的管道符|,没有将其传递给WSL的Shell,导致cut等命令被PowerShell本身识别而非WSL环境。同时双引号的转义处理也存在问题。

正确的执行方式

方法1:用单引号包裹WSL命令

PowerShell中,单引号内的内容不会被本地解析,会完整传递给WSL的Shell,这是最简洁的方式:

wsl -e sh -c 'HOSTIP=$(cat /etc/resolv.conf | grep nameserver | cut -b 12-); cd /tmp; mkfifo pip; nc -l -p 12345 < pip | nc ${HOSTIP} 12345 > pip'

方法2:转义PowerShell特殊字符

如果必须使用双引号,需要用反引号转义PowerShell会解析的管道符|`,同时修正变量转义:

wsl -e sh -c "HOSTIP=`$(cat /etc/resolv.conf `| grep nameserver `| cut -b 12-); cd /tmp; mkfifo pip; nc -l -p 12345 < pip `| nc `${HOSTIP} 12345 > pip"

封装为PowerShell函数

将命令封装成函数,方便重复调用:

function Invoke-WSLPortForward {
    wsl -e sh -c 'HOSTIP=$(cat /etc/resolv.conf | grep nameserver | cut -b 12-); cd /tmp; mkfifo pip; nc -l -p 12345 < pip | nc ${HOSTIP} 12345 > pip'
}

调用时直接执行 Invoke-WSLPortForward 即可。

额外注意事项

  • 确保WSL环境中已安装netcat(即nc命令),Debian/Ubuntu系可通过sudo apt install netcat-traditional安装。
  • WSL2中/etc/resolv.conf是动态生成的,这种方式获取主机IP可行,也可以用hostname -I或host.docker.internal(若有Docker环境)替代该IP获取逻辑。

内容的提问来源于stack exchange,提问作者kunal p

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:15:09