Sunday, July 6, 2008

I find it simply amazing that Powershell can use the .NET to find the Broadcast and Loopback with little complication, but not the host IP Address:
[System.Net.IPAddress]::Broadcast.IPAddressToString
or
[System.Net.IPAddress]::Loopback.IPAddressToString

I can find all NetworkInterface information BUT the IP easily enough:
[System.Net.NetworkInformation.NetworkInterface]::
GetAllNetworkInterfaces()

But if I want my local host IP address through .NET I need some kludge like:
$host_name = [System.Net.Dns]::GetHostName() ; [System.Net.Dns]::Resolve("$host_name")

Or I can dredge up some other not quite satisfactory kludge from gwmi:

$NetworkInfo =gwmi -query "SELECT * FROM Win32_NetworkAdapterConfiguration"
function NetworkInfoSort {$NetworkInfo | Select-Object IPAddress,Description,Index,DefaultIPGateway | sort-object Index}
NetworkInfoSort

gwmi -class win32_NetworkAdapterConfiguration | %{ $_.IPAddress }

gwmi -query "SELECT IPAddress FROM Win32_NetworkAdapterConfiguration" | Select IPAddress

I wish I could just do something like:

[System.Net.IPAddress]::LocalHost.IPAddressToString
or
[System.Net.NetworkInformation.NetworkInterface]::
GetAllNetworkInterfaces.IPAddress
or
Get-ipconfig

2 comments:

Ryan M. Ferris said...

Something like this also works but gets a little weird when you source the fields:

$hostnameX = [System.Net.Dns]::Resolve([System.Net.Dns]::GetHostName())

Ryan M. Ferris said...

/\/\o\/\/ came up with something interesting:
http://thepowershellguy.com/blogs/posh/archive/2008/06/30/powershell-get-ipconfig-function.aspx#16039

[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |% {$_.getIPProperties().UnicastAddresses[0]}

With some help this gets formatted lease times with IP Addresses

[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |% {$_.getIPProperties().UnicastAddress
es[0]} | Select Address, *Lifetime