Share via

One-liner PowerShell to set IP Address, DNS Servers, and Default Gateway

A fun part about configuring servers is that many servers still have static IP addresses.  The challenge is losing connectivity to the server when the configuration change is made.  Even with remote console access, this is an irksome task as it requires clicking through so many screens it’s just grrr…  (never mind that many of the remote console experiences are somewhat, shall we say, not on par with an RDP session).

Enter the PowerShell one liner:

&{$adapter = Get-NetAdapter -Name Ethernet;New-NetIPAddress -InterfaceAlias $adapter.Name -AddressFamily IPv4 -IPAddress -PrefixLength 24 -DefaultGateway; Set-DnsClientServerAddress -InterfaceAlias $adapter.Name -ServerAddresses ("","")}

Using this, at least gets the server configured and dynamic DNS configured (if using it), so all you have to do is run an ipconfig /flushdns on your client and your remote PowerShell session should reconnect.

Key things to know:

  • Requires PowerShell 3.0 – there are other examples out there for how to use PowerShell to invoke WMI to manage this for systems not yet on PowerShell 3.0.
  • “;” indicates separate commands.  This is not piping data from one command to the other here, it is running 3 separate commands using the variable defined in the first.
  • This isn't a script so there aren't any ExecutionPolicy considerations.
  • Specify the adapter name, in this case “Ethernet” as appropriate for your system.
  • Other commands to manage the TCP/IP settings are here:  Net TCP/IP Cmdlets in Windows PowerShell