Bat+PowerShell实现windows网络一键共享

当需要将笔记本WLAN通过 有线共享台式机 (同时可以便于远程),或者 虚拟机的虚拟适配器 时,由于win10关机共享失效,需要进控制面板反复点击,操作繁琐,本文给出脚本双击共享方案。
Bat+PowerShell实现windows网络一键共享_第1张图片

1. 新建文本文档,命名为ShareInternet.ps1

填充内容如下:

$NetShare = New-Object -ComObject HNetCfg.HNetShare
$wlan = $null
$ethernet = $null

foreach ($int in $NetShare.EnumEveryConnection) {
  $props = $NetShare.NetConnectionProps.Invoke($int)
  $a=$props.Name;
  "The name of adapter is: $a";
  if ($props.Name -eq "WLAN 2") {
    "==>[WLAN 2] is matched.";
    $wlan = $int;
  }

  if ($props.Name -eq "ETHERNET" ) {
    "==>[ETHERNET] is matched.";
    $ethernet = $int;
  }
}

$wlanConfig = $NetShare.INetSharingConfigurationForINetConnection.Invoke($wlan);
$ethernetConfig = $NetShare.INetSharingConfigurationForINetConnection.Invoke($ethernet);

"DisableSharing";
$wlanConfig.DisableSharing();
$ethernetConfig.DisableSharing();

"EnableSharing";
$wlanConfig.EnableSharing(0);
$ethernetConfig.EnableSharing(1);

"========== Done ==========";

Note: 建议将共享(桥接)的两网络适配器在控制面板-网络和 Internet-网络和共享中心-更改适配器重命名为英文名,在ps1文件中替换,避免中文名乱码(如“以太网”等)。

2. 新建xx.bat文件,填入内容

注意下面的.ps1文件路径匹配

PowerShell.exe -ExecutionPolicy Unrestricted -File "I:\MyShell\ShareInternet.ps1"

3. 双击运行

发送.bat文件快捷方式到桌面,右键以管理员身份运行即可。
还可以将该脚本加入开机启动,实现开机即共享。

你可能感兴趣的:(软件使用,网络,windows,脚本语言,powershell)