In this tutorial, I am going to show you how to configure a static IP address on a system that has one network card through PowerShell. This can come in handy when we have many servers that we are deploying and we would like to automate the IP addressing based on an Excel spreadsheet, for example, or if we are deploying using VMware customization templates.
This specific example will show you the exact commands needed to accomplish this. It is a basic tutorial and I do not include any steps on connecting to Excel through COM objects or anything of the sort.
If you want to do the same thing using the normal command prompt, read my previous post on setting a static IP address using the command prompt. Finally, you can also set a static IP address via Network and Sharing Center.
Configure Static IP using PowerShell
So let us dive right in. To start, make sure you open an administrator PowerShell window, otherwise you will get an Access is Denied error when trying to run the command below.
We will be using two PowerShell commands, New-NetIPAddress and Set-DNSClientServerAddress.
On the server that we want to configure, we open PowerShell and type the below command:
New-NetIPAddress –IPAddress <ip_address> -DefaultGateway <default_gateway> -PrefixLength <subnet_mask_in_bit_format> -InterfaceIndex (Get-NetAdapter).InterfaceIndex
Here is an example below:
New-NetIPAddress –IPAddress 192.168.1.13 -DefaultGateway 192.168.1.1 -PrefixLength 24 -InterfaceIndex (Get-NetAdapter).InterfaceIndex
All the arguments are self-explanatory, apart from the InterfaceIndex one. Over here instead of putting in the numerical value of the Interface Index, I just ran the Get-NetAdapter command inside my current command with filtering to output only the integer value of the Interface Index.
If you have multiple network adapters on your system, you can remove the function and simply enter the numerical value corresponding to the desired interface.
If the command completes successfully, we should get the result as shown below:
Now we have our IP Address, Subnet Mask and Default Gateway configured. However, one thing is missing. These are the DNS Server addresses.
To configure the DNS Server addresses, we run the following command:
Set-DNSClientServerAddress –InterfaceIndex (Get-NetAdapter).InterfaceIndex –ServerAddresses <ip1>,<ip2>, etc.
IP1 is the primary DNS Server, IP2 is the secondary and all the others are the third and so forth.
Here is an example:
Set-DNSClientServerAdress –InterfaceIndex (Get-NetAdapter).InterfaceIndex –ServerAddresses 192.1.68.1.1
That is it. Very simple and quick way to change IP settings for a network adapter using PowerShell. Any questions or comments are welcome! Enjoy!