This time to see how to initialize the network configuration using PowerShell, such as setting the IP address, subnet mask, etc., the first thing to say is that this is just an experimental script, not in a specific production environment has been tested, just to test something to write, so you need to test it yourself, Score but the script is not too complete, the main purpose is to try PowerShell in the network of the function of this block, in general, set the IP address and other information will be used in WMI to complete, but this time in particular to try to use the statement in PowerShell can be achieved, That's why this simple script
Below the code, this script also has a simple verification function, if the input is not an IP address, such as the letter symbol, and so on, the script will also appear error, the function of this block is mainly implemented using regular expressions
#首先查看当前计算机上的网络适配器信息 $i = 0${ip rules} = "\b[0-9]{1,3}\. [0-9] {1,3}\. [0-9] {1,3}\. [0-9] {1,3}\b "get-netadapter | ft -autosize name, interfacedescription, macaddress, InterfaceIndex, Status$netid = Read-Host "Please enter the network adapter number to set" foreach ($id in (get-netadapter) ifIndex) {if ($id -eq $netid) {$i ++}}if ($i -eq 0) { write-warning "The network adapter number entered does not exist";break}if (get-netadapter -interfaceindex $netid). status -eq "Disconnected") {"Current adapter not Connected"; break} $ip = Read-Host "Please enter the IP address to set" if ($ip -notmatch ${ip rules}) {write-warning "Please enter the correct IP address"; break} $dnsip = read-host "Please enter the IP address of the DNS server" if ($dnsip -notmatch ${ip rules}) {write-warning "Please enter the correct IP address"; Break} $mask = Read-Host "Please enter the length of the subnet mask" if (get-netadapter -interfaceindex $netid). status -eq "Disconnected") {Write-warning "The current adapter is not Connected";break}elseif (get-netadapter -interfaceindex $netid). status -eq "Up") {set-dnsclientserveraddress -interfaceindex $netid -serveraddresses $DNSIPIF ((get-netipaddress -interfaceindex $netid -addressfamily ipv4). Ipv4address.startswith ("169")) {new-netipaddress -interfaceindex $netid -IPAddress $ip -PrefixLength $mask}elseif (get-netipaddress -interfaceindex $netid - ADDRESSFAMILY IPV4). Ipv4address.startswith ("192")) {remove-netipaddress -interfaceindex $netid -AddressFamily ipv4new-netipaddress -interfaceindex $netid -IPAddress $ip -PrefixLength $mask}}
I have to say that the statement that sets the network adapter information in PowerShell feels like there is no WMI, but when it's time to try it, we'll have a chance to share more with you later.
This article is from the "Just Make It Happen" blog, so be sure to keep this source http://mxyit.blog.51cto.com/4308871/1652589
Initializing a network configuration using PowerShell