导语:需要通过管理员运行powershell,在里面输入一些命令。打算通过开机启动cmd脚本,通过cmd脚本 执行ps1脚本
问题:单独执行脚本会报错。
解决方式
需要在注册表的如下位置HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run创建字符Shadow,值为cmd脚本的位置。
以下是cmd脚本鹿筋
C:\Users\Administrator\Desktop\Shadow.cmd
打开powershell,采用unrestricted形式(否则无法执行脚本)
@set Path=%Path%;%SystemRoot%\system32\WindowsPowerShell\v1.0\& powershell -ExecutionPolicy Unrestricted "C:\Users\Administrator\Desktop\init.ps1"
exit
init.ps1脚本如下
# 获取 Windows 和 WSL2 的 ip
# $winip = bash.exe -c "ip route | grep default | awk '{print `$3}'"
# default via 172.20.16.1 dev eth0
$winip = bash.exe -c "ip route | grep default |cut -d ' ' -f 3"
# $wslip = bash.exe -c "hostname -I | awk '{print `$1}'"
# 172.20.30.87 172.16.10.174 172.18.0.1 172.17.0.1
$wslip = bash.exe -c "hostname -I |cut -d ' ' -f 1 "
$found1 = $winip -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$found2 = $wslip -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( !($found1 -and $found2) ){
# 如果没找到 wsl 的 ip, 就退出执行
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
# 你需要映射到局域网中端口
$ports=@(80,81,22222,22,800,11380,11381);
# 监听的 ip,这么写是可以来自局域网
$addr='0.0.0.0';
# 监听的端口,就是谁来访问自己
$ports_a = $ports -join ",";
# 移除旧的防火墙规则
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' " | Out-Null
# 允许防火墙规则通过这些端口
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP" | Out-Null
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP" | Out-Null
# 使用 portproxy 让 Windows 转发端口
# https://docs.microsoft.com/en-us/windows-server/networking/technologies/netsh/netsh-interface-portproxy
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr" | Out-Null
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$wslip" | Out-Null
}
添加开机启动
搜索计算机管理 选择任务计划任务
以下面模版创建任务
缺点:每次开机会打开ps1这个脚本文件。容易被人手滑修改。
参考
https://www.programminghunter.com/article/19961163124/
https://zhuanlan.zhihu.com/p/20628937
https://blog.minifish.org/posts/powershell-starttup/
https://blog.csdn.net/Jmilk/article/details/50661936