PowerShell Direct + Hot Add NIC == Give me an IP address

Here is a fun script snippet that is possible with Windows 10:

function addNicWithIP([string]$VMName,$cred, [string]$Switch, [string]$IPaddress, [string]$subnetPrefixLength){
   $newNetAdapter = Add-VMNetworkAdapter -VMName $VMName -SwitchName $Switch -Passthru
   Write-Output “[$($VMName)]:: Wait for IP address and create virtual switch”
   waitForPSDirect $VMName $cred
   icm -VMName $VMName -Credential $cred {
      param($IPAddress, $subnetPrefixLength, $MacAddress)
      # Wait for the NIC to appear
      do {sleep 1} until (@(get-netadapter | ? PermanentAddress -eq $MacAddress).Count -eq 1)
      # Setup IP Address
      New-NetIPAddress -IPAddress $IPAddress `
                       -InterfaceAlias (get-netadapter | ? PermanentAddress -eq $MacAddress).Name `
                       -PrefixLength $subnetPrefixLength
      } -ArgumentList $IPAddress, $subnetPrefixLength, $newNetAdapter.MacAddress

What this does is:

  1. Adds a new network adapter to a running virtual machine
  2. Finds the new network adapter inside the virtual machine
  3. Assigns a static IP address to the new network adapter

You can call it like this:

addNicWithIP -VMName “PowerShell Container” -cred $localCred -Switch “Virtual Switch” -IPaddress “” -subnetPrefixLength “24”