31
I'm writing PowerShell code to get all the local IPv4 addresses, excluding the loopback one. I need something like the LINQ SelectMany method, but I can't figure out how to do this with PS filters. This is the code I have so far, which works using a plain old ArrayList:
function Get-Computer-IP-Address()
{
$ipAddresses = New-Object System.Collections.ArrayList
$networkAdaptersWithIp = Get-WmiObject Win32_NetworkAdapterConfiguration | ? { $_.IPAddress -ne $null }
foreach ($networkAdapter in $networkAdaptersWithIp)
{
foreach ($ipAddress in $networkAdapter.IPAddress)
{
if ($ipAddress -notlike "127.*" -and $ipAddress -notlike "*::*")
{
$ipAddresses.Add($ipAddress)
}
}
}
if ($ipAddresses.Length -eq 0)
{
throw "Failed to find any non-loopback IPv4 addresses"
}
return $ipAddresses
}
I'd like to know if there's a cleaner way to do it, with less code.