求助:WSL2端口转发PowerShell脚本运行报错排查
报错内容(翻译自截图)
- 第2行字符1处语法错误:缺少语句终止符或表达式中的分隔符。
- 无法将“$found”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。
问题点说明及修复方案
第一行bash命令未闭合引号
原脚本第一行的bash命令双引号未闭合,导致PowerShell解析逻辑混乱。需将bash命令完整包裹在双引号内:
错误写法:$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '
正确写法:$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"端口数组范围写法错误
PowerShell中表示连续端口范围需用..而非-,原脚本里的50000-55000不会被识别为端口范围,会导致后续端口处理失败。修改为:
错误写法:$ports=@(81,80,433,443,10000,3000,5000,50000-55000);
正确写法:$ports=@(81,80,433,443,10000,3000,5000,50000..55000);WSL中ifconfig命令可能不存在
多数现代WSL发行版默认不再预装ifconfig,建议改用ip命令提取IP,稳定性更强:
替换第一行为:$remoteport = bash.exe -c "ip addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'"避免不必要的
iex调用
原脚本用iex执行PowerShell cmdlet和系统命令,存在安全风险且不规范,直接调用命令即可。比如把iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";改为Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -ErrorAction SilentlyContinue;(加-ErrorAction SilentlyContinue避免规则不存在时报错)
修复后的完整脚本
# 获取WSL2的IP地址 $remoteport = bash.exe -c "ip addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'" $found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'; if( $found ){ $remoteport = $matches[0]; } else{ Write-Host "脚本退出,无法找到WSL 2的IP地址"; exit; } #[端口配置] # 需要转发的所有端口,用逗号分隔,连续范围用..表示 $ports=@(81,80,433,443,10000,3000,5000,50000..55000); #[本地静态IP] # 可修改为你的本地IP,监听特定地址 $addr='192.168.100.3'; $ports_a = $ports -join ","; # 删除旧的防火墙规则(规则不存在时不报错) Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -ErrorAction SilentlyContinue; # 添加入站和出站防火墙规则 New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP; New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP; # 配置端口转发 foreach( $port in $ports ){ # 删除旧的转发规则 netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr | Out-Null # 添加新的转发规则 netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport }
内容的提问来源于stack exchange,提问作者Jiří Bezděkovský

