Here is another solution:
$env:HostIP = (
Get-NetIPConfiguration |
Where-Object {
$_.IPv4DefaultGateway -ne $null -and
$_.NetAdapter.Status -ne "Disconnected"
}
).IPv4Address.IPAddress
You'll need to achieve what you want.Select-Object
The
cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array.Select-Object
When I want to get specific properties, I always run the command I want with (alias for fl *) to get all the properties returned that exist. e.g:Format-List *
PS C:\Windows\system32> Get-NetAdapter | Get-NetIPAddress | fl *
PrefixOrigin : Dhcp
SuffixOrigin : Dhcp
Type : Unicast
Store : ActiveStore
AddressFamily : IPv4
AddressState : Preferred
ifIndex : 14
Caption :
Description :
ElementName :
InstanceID :
CommunicationStatus :
DetailedStatus :
HealthState :
InstallDate :
Name : ;:8:8:8;>:55;>55;55;
OperatingStatus :
OperationalStatus :
PrimaryStatus :
Status :
StatusDescriptions :
AvailableRequestedStates :
EnabledDefault : 2
EnabledState :
OtherEnabledState :
RequestedState : 12
TimeOfLastStateChange :
TransitioningToState : 12
CreationClassName :
SystemCreationClassName :
SystemName :
NameFormat :
OtherTypeDescription :
ProtocolIFType : 4096
ProtocolType :
Address :
AddressOrigin : 0
AddressType :
IPv4Address : 10.0.0.140
IPv6Address :
IPVersionSupport :
PrefixLength : 24
SubnetMask :
InterfaceAlias : Ethernet
InterfaceIndex : 14
IPAddress : 10.0.0.140
PreferredLifetime : 6.21:47:25
SkipAsSource : False
ValidLifetime : 6.21:47:25
PSComputerName :
CimClass : ROOT/StandardCimv2:MSFT_NetIPAddress
CimInstanceProperties : {Caption, Description, ElementName, InstanceID...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
Then I know what properties fit my needs and I can select the ones I want. You can use:
Get-NetAdapter | Get-NetIPAddress | Select-Object InterfaceAlias, IPAddress | Format-Table
But keep in mind that the is only used for you to view it. If you need to do something else with the returned properties, omit the Format-Table.Format-Table
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(ip.Address.ToString());
}
}
}
}
This should get you what you want. ip.Address is an IPAddress, that you want.