bat+powershell实现win10一键共享

网卡Ethernet共享给网卡Ethernet2

C:\tools\share_net.ps1

# Register the HNetCfg library (once)
# regsvr32 hnetcfg.dll

# Create a NetSharingManager object
$m = New-Object -ComObject HNetCfg.HNetShare

# List connections
$m.EnumEveryConnection |% { $m.NetConnectionProps.Invoke($_) }

# Find connection
$c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq "Ethernet" }
$c2 = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq "Ethernet2" }

# Get sharing configuration
$config = $m.INetSharingConfigurationForINetConnection.Invoke($c)
$config2 = $m.INetSharingConfigurationForINetConnection.Invoke($c2)

# See if sharing is enabled
Write-Output $config.SharingEnabled
Write-Output $config2.SharingEnabled

# See the role of connection in sharing
# 0 - public, 1 - private
# Only meaningful if SharingEnabled is True
# Write-Output $config.SharingType
# Write-Output $config2.SharingType

# pause
Start-Sleep -s 1

# Disable sharing
"Disable sharing"
$config.DisableSharing()
$config2.DisableSharing()

# pause
Start-Sleep -s 3

# Enable sharing (0 - public, 1 - private)
"Enable sharing"
$config.EnableSharing(0)
$config2.EnableSharing(1)

# pause
Start-Sleep -s 3

"Reconfig IP"
netsh interface set interface "Ethernet2" admin=disable
Start-Sleep -s 1
netsh interface ip del address "Ethernet2" 192.168.0.146
Start-Sleep -s 1
netsh interface set interface "Ethernet2" admin=enable

Start-Sleep -s 1
netsh interface ip add address "Ethernet2" 192.168.0.146 255.255.255.0
Start-Sleep -s 1

pause

bat:

PowerShell.exe -ExecutionPolicy Unrestricted -File "C:\tools\share_net.ps1"

参考:
https://blog.csdn.net/qq_34907927/article/details/123120398
https://superuser.com/questions/470319/how-to-enable-internet-connection-sharing-using-command-line

posted @ 2024-02-18 11:24  hgrun  阅读(90)  评论(0编辑  收藏  举报