win10开机启动ps1脚本

导语:需要通过管理员运行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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爷来辣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值