Windows Server 2019 Automation with PowerShell Cookbook
上QQ阅读APP看书,第一时间看更新

Configuring IP addresses from static to DHCP

In some cases, you may need to switch the IP address of a server from static back to DHCP. The server may have had a static IP address based on the role it used to perform a role, but you plan to repurpose this server and want to reconfigure the server to obtain IP configuration from DHCP.

Getting ready

This recipe uses SRV1 which, at the start of the recipe, has manual IP configuration, such as what you created in the Configure IP addressing recipe. In this recipe, you changed from static to DHCP configuration. Also, this recipe assumes that you have DHCP running based on the Installing and authorizing a DHCP server and the Configuring DHCP scopes recipes.

How to do it...

  1. Get the existing IP address' information:
    $IPType = 'IPv4'
    $Adapter = Get-NetAdapter |
                 Where-Object Status -eq 'up'
    $Interface = $Adapter |
                   Get-NetIPInterface -AddressFamily $IPType
    $IfIndex = $Interface.ifIndex
    $IfAlias = $Interface.Interfacealias
    Get-NetIPAddress -InterfaceIndex $Ifindex -AddressFamily $IPType
  2. Set the interface to get its address from DHCP:
    Set-NetIPInterface -InterfaceIndex $IfIndex -DHCP Enabled
  3. Test the results:
    Get-NetIPAddress -InterfaceIndex $Ifindex -AddressFamily $IPType

How it works...

In step 1, you checked the IP address assigned to SRV1, which is manually configured. The output of this step looks like this:

In step 2, you set the NIC to get its IP configuration via DHCP. This step produces no output.

In step 3, you checked the results of changing back to DHCP, which look like this:

There's more...

In step 3, you obtained the IP address for SRV1 using Get-NetIPAddress. As noted in the New ways to do old things recipe, you could have used ipconfig.exe for a faster result.