Share via


PowerShell Direct & Waiting for an IP Address

Here is an interesting problem.  With PowerShell Direct it is possible to get connected to a PowerShell session inside a virtual machine before the virtual machine has received an IP address.  While this is cool - it can result in annoying script failures.  To handle this - if I am using PowerShell Direct and I need to get something from the network I first run this:

# Wait for DHCP
while ((Get-NetIPAddress | ? AddressFamily -eq IPv4 | ? IPAddress -ne 127.0.0.1).SuffixOrigin -ne "Dhcp") {sleep -Milliseconds 10}

The nice thing about this snippet is that it is not looking for a specific subnet or IP address - it is just waiting to receive a DHCP lease from somewhere.  This means that it works no matter what network I am connected to.

Cheers,
Ben