Powershell: Configure a static IP on an unplugged NIC

Solution 1:

You need to remove the existing DHCP IP address already assigned to the adapter. You should also set the DNS server for the interface. I provided an example below, but replace the xxx.xxx.xxx.xxx with your DNS Server IP Address.

You'll need to disable DHCP in the registry for this interface in the PersistentStore before you can set the IP address.

Set-ItemProperty -Path “HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\$((Get-NetAdapter -InterfaceIndex 10).InterfaceGuid)” -Name EnableDHCP -Value 0
Remove-NetIpAddress -InterfaceIndex 10 -AddressFamily IPv4
Remove-NetRoute -InterfaceIndex 10 -AddressFamily IPv4 -Confirm:$false
New-NetIpAddress -InterfaceIndex 10 -IpAddress 192.168.9.10 -PrefixLength 24 -DefaultGateway 192.168.9.1 -AddressFamily IPv4
Set-DnsClientServerAddress -InterfaceIndex 10 -ServerAddresses "xxx.xxx.xxx.xxx"

This website has a good example and explanation of the process: https://www.pdq.com/blog/using-powershell-to-set-static-and-dhcp-ip-addresses-part-1/

This website talks about the same problem you're having and their solution: http://www.darrylvanderpeijl.com/inconsistent-parameters-policystore-persistentstore-and-dhcp-enabled/

Solution 2:

I had issues on windows 10 1909 with all code I found, it seemed inconsistent. The below code works for me, choose netsh or powershell exclusive code:

$IP = $builddata.templateIP
$SubnetMaskBits = $builddata.Subnetmaskbits
$SubnetMask = $builddata.Subnetmask
$Gateway = $builddata.gateway
$Dns = $builddata.DNS1,$builddata.DNS2

$IPType = "IPv4"
$adapter = Get-NetAdapter | Where-Object {$_.InterfaceDescription -like "vmx*"} #looking for vmxnet3

# you can use either at this point
# via netsh

netsh interface ipv4 set interface $adapter.InterfaceIndex dadtransmits=0 store=persistent
netsh interface ip set address name="$($adapter.name)" static $IP $SubnetMask $Gateway 1

# via PowerShell

$adapter | Get-NetIPInterface | ? {$_.addressfamily -eq  $IPType} | % {Get-NetIPAddress | Remove-NetIPAddress -Confirm:$false}
$adapter | Get-NetIPInterface | New-NetIPAddress `
     -AddressFamily $IPType `
     -IPAddress $IP `
     -PrefixLength $SubnetMaskBits `
     -DefaultGateway $Gateway -Confirm:$false