指定网卡名修改网关

2023-12-04 11:25:31 浏览数 (1)

虽然已经测试过多种Windows系统能用,但不能保证适用各种情况,毕竟系统环境千差万别,建议先打快照,快照转镜像买台按量计费的临时测试机的机器来验证,验证没问题再用

代码语言:javascript复制
#获取网卡名
$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 "HKLMSYSTEMCurrentControlSetServicesTcpipParametersInterfaces$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:SYSTEMCurrentControlSetServicesTcpipParametersInterfaces$interfaceGuid"
    REG ADD "HKLMSYSTEMCurrentControlSetServicesTcpipParametersInterfaces$interfaceGuid" /v DefaultGatewayMetric /t REG_MULTI_SZ /d "1" /f
    REG ADD "HKLMSYSTEMCurrentControlSetServicesTcpipParametersInterfaces$interfaceGuid" /v DefaultGateway /t REG_MULTI_SZ /d "$gw" /f
    REG ADD "HKLMSYSTEMCurrentControlSetServicesTcpipParametersInterfaces$interfaceGuid" /v DhcpDefaultGateway /t REG_MULTI_SZ /d "$gw" /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

0 人点赞