- Windows Server 2019 Automation with PowerShell Cookbook
- Thomas Lee
- 321字
- 2021-03-26 16:20:51
Configuring IP addressing
By default, Windows uses DHCP to configure any NICs that are found during the installation process. Once you complete the installation of Windows, you can use the settings application netsh.exe
, or, of course, PowerShell to set IP configuration manually.
Getting ready
This recipe runs on SRV2.Reskit.Org
. This host is a domain-joined system with an NIC that is initially set up to be configured from DHCP.
How to do it...
- Get existing IP address information for
SRV2
:$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
- Set the IP address for
SRV2
:$IPHT = @{ InterfaceAlias = $IfAlias PrefixLength = 24 IPAddress = '10.10.10.51' DefaultGateway = '10.10.10.254' AddressFamily = $IPType } New-NetIPAddress @IPHT | Out-Null
- Set the DNS server details:
$CAHT = @{ InterfaceIndex = $IfIndex ServerAddresses = '10.10.10.10' } Set-DnsClientServerAddress @CAHT
- Test the new configuration:
Get-NetIPAddress -InterfaceIndex $IfIndex -AddressFamily IPv4 Test-NetConnection -ComputerName DC1.Reskit.Org Resolve-DnsName -Name SRV2.Reskit.Org -Server DC1.Reskit.Org | Where-Object Type -eq 'A'
How it works...
In step 1, you examined the current IP configuration for SRV2
, which looks like this:
In step 2, you set a static IP address for the NIC in SRV2
, which produces no output. In step 3, you set the DNS server IP address, which also produces no output.
In step 4, you tested the new IP configuration, which looks like this:
There's more...
In step 1, you used the Get-NetIPConfiguration
cmdlet. Two other closely related cmdlets that were not shown in the recipe are Get-NetIPInterface
and Get-NetAdapter
. Both provide additional information about the network adapter/network interface.
In step 4, you checked the IP configuration by using Get-NetIPAddress
to show the IP address and subnet mask. You could have used the Get-NetIPConfiguration
cmdlet to return the IP address and subnet mask, plus details of the default gateway and your DNS server IP address.