Поделиться через


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 192.168.1.55 -PrefixLength 24 -DefaultGateway 192.168.1.1; Set-DnsClientServerAddress -InterfaceAlias $adapter.Name -ServerAddresses ("192.168.1.2","192.168.1.3")}

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

  • Anonymous
    January 01, 2003
    The comment has been removed
  • Anonymous
    January 01, 2003
    '&' is an operator that means to run the following string as a command. http://technet.microsoft.com/en-us/library/hh847732.aspx

    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.
  • Anonymous
    January 01, 2003
    Nice, handier for me than netsh!
  • Anonymous
    June 26, 2014
    what does the & mean?
    Thanks
  • Anonymous
    May 12, 2016
    The comment has been removed
  • Anonymous
    July 14, 2016
    The comment has been removed