2019.8.24

老规矩,转载不打招呼的至少把原文链接摆到最前面。另外限于本人要准备考研,今天发文只是没管住手,半年内没空完善,敬请谅解。


原文链接:https://blog.51cto.com/12078224/2432278

系统环境:Windows 10 1903 Pro


背景:在学校用机房的网线插到自己电脑上上网,但需要改为固定的IP、默认网关,DNS也可以改。每次都从电脑右下角进入更改网络适配器选项太麻烦了,网上能查到用命令行修改IP的办法基本都是netsh,想用cmd结果来个这么个提示:

图片.png

图一

追求技术最前线,于是乎用powershell试试,cmd的话保存成文件是bat,powershell的话文件就保存为ps1。


正文

下图是我的目标配置:图片.png

图二


下图是我电脑里原先的上网配置:

图片.png

图三


Get-NetIPAddress
https://docs.microsoft.com/en-us/powershell/module/nettcpip/get-netipaddress?view=win10-ps
根据这个文档,可以执行Get-NetIPAddress -AddressFamily IPv4查看本地IPv4网络配置,相当于cmd的ipconfig了:

图片.png

这里解释一些参数:AddressFamily,可以设为IPv4或IPv6;InterfaceIndex接口序号,InterfaceAlias接口别名,在网上看到的这些英文网站似乎都是以index为12举例的,即有线网络的适配器;PrefixLength : 16,这个就是子网掩码写成/x的形式,CIDR嘛。


New-NetIPAddress
https://docs.microsoft.com/en-us/powershell/module/nettcpip/new-netipaddress?view=win10-ps

The first command adds a new IPv4 address to the network interface at index 12. The PrefixLength parameter specifies the subnet mask for the IP address. In this example, the PrefixLength of 24 equals a subnet mask of 255.255.255.0. When you add an IPv4 address, the address specified for the Default Gateway must be in the same subnet as the IPv4 address that you add.

上面英文大家应该都能看得懂,就是IP和默认网关在同一子网下。

PS C:\WINDOWS\system32> New-NetIPAddress -InterfaceIndex 12 -IPAddress 192.168.80.83 -PrefixLength 24  
图片.png


这样就配置完了图三的上面第一个框,之后要配DNS才能让电脑上网:

Set-DnsClientServerAddress
https://docs.microsoft.com/en-us/powershell/module/dnsclient/set-dnsclientserveraddress?view=win10-ps

PS C:\WINDOWS\system32> Set-DNSClientServerAddress -InterfaceIndex 12 -ServerAddresses 211.111.111.1,211.111.111.12

这样就配完了图三剩下DNS的两行,上面命令里的DNS是我瞎写的,中间半角逗号分隔。

保存为308.ps1:

图片.png

powershell里运行:.\1.ps1(测试用,改名了)

图片.png


如果修改这个IP为192.168.80.83,我觉得是这个操作:(没有实现

Set-NetIPAddress
https://docs.microsoft.com/en-us/powershell/module/nettcpip/set-netipaddress?view=win10-ps

如果删除配置的IP,

Remove-NetIPAddress
https://docs.microsoft.com/en-us/powershell/module/nettcpip/remove-netipaddress?view=win10-ps

下图我敲了两次回车。最终结果是删掉了图三的前两行,配置了的默认网关和DNS没有删掉。
图片.png


现在存在的问题:

1.powershell改网络配置要有管理员权限,直接双击改不了。

https://www.windows10.pro/right-click-menu-run-as-administrator-ps1/

试了但没用。

2.怎么把已经配好的手动状态换回原来的自动获取状态暂时还不清楚。


其他参考链接:

Configure Static IP Address on a Network Adapter using PowerShell
https://thebackroomtech.com/2018/04/16/configure-static-ip-address-on-network-adapter-using-powershell/


How to Change Your IP Address Using PowerShell
https://www.howtogeek.com/112660/how-to-change-your-ip-address-using-powershell/


PowerShell2.0之维护网络(三)设置网络适配器 - @天行健中国元素 - 博客园
https://www.cnblogs.com/fuhj02/archive/2011/01/24/1942786.html

PowerShell 4.0实现自动化设置服务器_PowerShell_脚本之家
https://www.jb51.net/article/72738.htm

Set-DnsClientServerAddress -InterfaceIndex 12 -ResetServerAddresses可以清除掉图三DNS的配置。


PowerShell设置DHCP自动获取IP地址 - PowerShell - 洪哥笔记
http://www.splaybow.com/post/powershell-dhcp-set.html