PowerShell Tip of the Week: Get IP address

There are multiple ways to get IP address information. Most common are ipconfig or Get-NetIPAddress command. Today I want to show you how to check this quickly using ping class.

Get IP address

To check IP configuration we can use one of the following one-liner commands

Ipconfig /all

#or

$IPAddress = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.Ipaddress.length -gt 1} 
$IPAddress.ipaddress[0]  

#or

Get-NetIPAddress -AddressState Preferred -AddressFamily IPv4 | Select-Object IPAddress,InterfaceAlias

#or

Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred"} | Sort-object IPAddress | Format-Table -Wrap -AutoSize

#or

$Servers = Get-Content -path "c:\users\$env:username\desktop\servers.txt"
Test-Connection $Servers -count 1 | Select-Object @{Name="Computername";Expression={$_.Address}},Ipv4Address

Our script is based on .NET Framework System.Net.NetworkInformation ping class:

$Server = "DC01"
$ping = New-Object System.Net.NetworkInformation.Ping
$ServerIP = ($ping.Send($Server).Address)

#Check it in one-liner script
$ping = New-Object System.Net.NetworkInformation.Ping
Get-Content -path C:\users\$env:username\desktop\servers.txt | foreach { "{0} - {1}" -f $_, ($ping.Send($_).Address) }

Output:
Results will be displayed in console and at the end saved into CSV file.

Get IP Address
Get IP Address

Final script:


    $Servers = Get-Content -path "c:\users\$env:username\desktop\servers.txt"
    $Array = @()
    $ping = New-Object System.Net.NetworkInformation.Ping

    #Looping each server
    Foreach($Server in $Servers)
    {
        $ServerIP = $null
        $Object = $null
        $Value = $null

        # Ping server
        $ServerIP = ($ping.Send($Server).Address)

        If($ServerIP)
        {
            $Value = $ServerIP.IPAddressToString
        }
        Else
        {
            $Value = "(not found)"
        }

        # Create object 
        $Object = New-Object PSObject -Property ([ordered]@{ 
  
                Server                  = $Server
                IPAddress               = $Value
  
            }) 
             
        # Add object to array
        $Array += $Object

        #Display object
        $Object
    }

    If($Array)
    {
        #Save CSV file with results
        $Array | Export-Csv -Path C:\users\$env:username\desktop\IPAddresses.csv -NoTypeInformation
    }

If ping command doesn’t work due to some firewall limitations there is another way – [System.Net.Dns]

$Server = "ADFSO1"
$DNSCheck = ([System.Net.Dns]::GetHostByName(("$Server")))
$IP = $DNSCheck.addresslist.ipaddresstostring

Using this class you can also check FQDN for server – I added article about it – link.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.