How to set or change IP configuration using a powershell script

How to set or change IP configuration using a powershell script

 

In this blog post, I’ll show you How to set or change IP configuration using a powershell script on both client and server.

In the script, I’ll be using three Microsoft PowerShell modules that are part of the default PowerShell 3 and above Installation.

The modules that I’ll be using are:

  • Network Adapter Module – This module manages the Network Adapter on the computer
  • Net TCP/IP Module – This module controls the TCP/IP configuration on the adapter like IP, DG, etc
  • DNS Client Module – This module controls the DNS client settings on the computer

The code In this article Is very handy during deployments when the Virtual Machine configuration Is scripted or when doing remote support with non-technical people.

To complete this you will need Windows PowerShell 3 and above and a Local or domain admin account on the machine.

To get started, I’ll use the cmdlet below to get the Network adapter ID using the line:

Get-NetAdapter | select Name, IfIndex
How to set or change IP configuration using a powershell script
How to set or change IP configuration using a powershell script

In my case, the Interface ID Is 4 and I’ll use it reference the NIC In the next line of code.

Once I have the Interface ID, I’ll set the IP Address, Subnet and Default Gateway using the code:

TCP Details will be:

IP: 192.168.200.10

Sub: 255.255.255.0

DG: 192.168.200.1

The code below contains all the details the machine needs to communicate.

New-NetIPAddress -IPAddress 192.168.200.10 -InterfaceIndex 4 -PrefixLength 24 -DefaultGateway 192.168.200.1
How to set or change IP configuration using a powershell script
How to set or change IP configuration using a powershell script

Next, I’ll set the DNS Server using the cmdlet below:

DNS IP will be: 192.168.200.12

Set-DnsClientServerAddress -InterfaceIndex 4 -ServerAddresses 192.168.200.12

Now, when I type ipconfig I can see the new configuration

If you are looking for more advance code you could use variables as seen below.

$ip = 192.168.200.10

$dg = 192.168.200.1

$prf = 24

$int = 4

New-NetIPAddress -IPAddress $ip -InterfaceIndex $int -PrefixLength $prf -DefaultGateway $dg

You could even use, input from the user using the code:

$ip = read-host " Type IP Address"




Search blogs




Bitnami