虽然已经测试过多种Windows系统能用,但不能保证适用各种情况,毕竟系统环境千差万别,建议先打快照,快照转镜像买台按量计费的临时测试机的机器来验证,验证没问题再用
#获取网卡名
$NICName=(Get-WmiObject Win32_NetworkAdapter -Filter 'NetEnabled=True').NetConnectionID
#显性指定网关地址
$gw="172.16.4.1" #网关具体化成你自己的
#显性设置网关(先删后加)
route delete 0.0.0.0
#route add 0.0.0.0 mask 0.0.0.0 $gw
#route add -p 0.0.0.0 mask 0.0.0.0 $gw
netsh interface ipv4 add route prefix=0.0.0.0/0 interface=$NICName nexthop=$gw
#getgw
$gw=(Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'").defaultipgateway
if([string]::IsNullOrEmpty($gw)){
$gw=(Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'").DHCPServer
}
if([string]::IsNullOrEmpty($gw)){
$interface = (Get-WmiObject Win32_NetworkAdapter -Filter 'NetEnabled=True').GUID
$string=reg query "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interface" | findstr /i DhcpServer
$gw = $string -split '\s+' | Select-Object -Last 1
}
#set route metric
$NICName=(Get-WmiObject Win32_NetworkAdapter -Filter 'NetEnabled=True').NetConnectionID
foreach ($interfacename in $NICName) {
netsh interface ip set interface interface="$interfacename" metric=1
}
#set defaultgw metric
$interfaces = Get-WmiObject Win32_NetworkAdapter -Filter 'NetEnabled=True' | ForEach-Object { $_.GUID }
foreach ($interfaceGuid in $interfaces) {
$registryPath = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceGuid"
REG ADD "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceGuid" /v DefaultGatewayMetric /t REG_MULTI_SZ /d "1\0" /f
REG ADD "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceGuid" /v DefaultGateway /t REG_MULTI_SZ /d "$gw\0" /f
REG ADD "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceGuid" /v DhcpDefaultGateway /t REG_MULTI_SZ /d "$gw\0" /f
}
#以上代码执行完成后,检查网关是否为空,为空则重启机器
write-host > C:\checkgw.ps1
"if( [string]::IsNullOrEmpty( (Get-WmiObject win32_networkadapterconfiguration -filter `"ipenabled = 'true'`").defaultipgateway ) ){restart-computer -force};Remove-Item `$MyInvocation.MyCommand.Path -force 2>&1 >`$null;" | Out-File -Append C:\checkgw.ps1 -encoding ascii
powershell -file C:\checkgw.ps1
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。