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

Comments (6)

  1. Correction… I’ve added the ‘&’ operator back in apparently pulling it out breaks the syntax.

    It looks like a "script block", which is the portion of the command enclosed in the curly brackets, is treated as a string. Since it treats said script block as a string as a string, the ‘&’ character is required to execute the script block.

  2. ‘&’ is an operator that means to run the following string as a command.

    Thank you for catching this, it is an artifact from the script I was writing. The script builds the string syntax in the variable and then it executes the string.

    I have updated the post to remove the ‘&’ character.

  3. Nice, handier for me than netsh!

  4. me says:

    what does the & mean?

  5. pregunton says:

    How can I get NetAdapter list ?

    I want set DNS servers (primary, secondary and other), Get IP automatic. And add 4 DNS sufix.

    is it posible using script ps1 ?

  6. Don says:

    If the IP Address is already in place and you made a to change a DNS / IP etc this WILL ERROR OUT (because the OLD values need removing) – could you be so kind as to show us how to remove existing before your step …….:) please …… ? :).

Skip to main content