Skip to content

Instantly share code, notes, and snippets.

@grantcarthew
Created October 16, 2013 00:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantcarthew/7000687 to your computer and use it in GitHub Desktop.
Save grantcarthew/7000687 to your computer and use it in GitHub Desktop.
Determine the active IP address on a Windows machine with PowerShell. http://uglygizmo.blogspot.com.au/
<#
.Synopsis
Returns IPv4 address details for the local machine.
Information is gathered from the active interface being used by the default route.
#>
[CmdletBinding()]
[OutputType([string])]
Param ()
Write-Verbose -Message ("Begin: " + $MyInvocation.MyCommand.Path)
<#
.Synopsis
This function uses regular expressions to return the first IPv4
dotted decimal notation string in the list of strings passed.
#>
function Get-First
{
[CmdletBinding()]
[OutputType([string])]
Param( $List )
[Regex]$reg = "\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}"
$result = ""
foreach ($ip in $List)
{
$match = $reg.Match($ip)
if ($match.Success)
{
$result = $match.Groups[0].Value
break
}
}
$result
}
Write-Verbose -Message "Getting the interface index being used by the default route."
$NICIndex = Get-CimInstance -ClassName Win32_IP4RouteTable |
Where-Object { $_.Destination -eq "0.0.0.0"-and $_.Mask -eq "0.0.0.0" } |
Sort-Object Metric1 |
Select-Object -First 1 |
Select-Object -ExpandProperty InterfaceIndex
Write-Verbose -Message "Getting the default route network adapter configuration."
$AdapterConfig = Get-CimInstance -ClassName Win32_NetworkAdapter |
Where-Object { $_.InterfaceIndex -eq $NICIndex } |
Get-CimAssociatedInstance -ResultClassName Win32_NetworkAdapterConfiguration
Write-Verbose -Message "Populating a custom PSObject with the desired details."
$ipconfig = [PSCustomObject]@{Description = $AdapterConfig.Description;
MACAddress = $AdapterConfig.MACAddress;
Address = (Get-First $AdapterConfig.IPAddress);
NetMask = (Get-First $AdapterConfig.IPSubnet);
Gateway = (Get-First $AdapterConfig.DefaultIPGateway);
DHCPServer = $AdapterConfig.DHCPServer;
DNSHostName = $AdapterConfig.DNSHostName;
DNSDomain = $AdapterConfig.DNSDomain;
DNSSearch = $AdapterConfig.DNSDomainSuffixSearchOrder}
# Return the result.
$ipconfig
Write-Verbose -Message ("End: " + $MyInvocation.MyCommand.Path)
@MichaelWerner
Copy link

MichaelWerner commented Jan 7, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment