Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Get IP Data

Posted on March 10, 2011June 28, 2013

I was doodling in PowerShell this morning and ended up with what I hope is a useful function to retrieve IP configuration information, sort of like IPCONFIG, but using WMI. The beauty is that I can connect to remote machines and the output is an object which leads to all sorts of possibilities.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

My function is called Get-IPData.

Function Get-IPData {
#this function assumes admin credentials
[cmdletBinding()]
Param(
    [Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [ValidateNotNullOrEmpty()]
    [Alias("name")]
    [string[]]$computername=$env:computername
)

Process {
    ForEach ($computer in $computername) {
        Write-Verbose "Querying $($computer.ToUpper())"
        Try 
        {
            #get NICS that are IP and DHCP enabled
            Get-WMIObject -Class win32_networkadapterconfiguration -computername $Computer `
            -Filter "IPEnabled='TRUE' AND DHCPEnabled='TRUE'" -ErrorAction "Stop" | 
            Select Description,DNSHostname,
            @{Name="IPAddress";Expression={$_.IPAddress[0]}},
            @{Name="SubnetMask";Expression={$_.IPSubnet[0]}},
            @{Name="DefaultGateway";Expression={$_.DefaultIPGateway[0]}},DNSDomain,
            @{Name="PrimaryDNS";Expression={$_.DNSServerSearchOrder[0]}},DHCPServer,
            @{Name="DHCPLease";Expression={$_.ConvertToDateTime($_.DHCPLeaseObtained)}},
            @{Name="DHCPExpires";Expression={$_.ConvertToDateTime($_.DHCPLeaseExpires)}},
            @{Name="DHCPTimeToLive";Expression={ $_.ConvertToDateTime($_.DHCPLeaseExpires) - (Get-Date)}},
            MACAddress,
            @{Name="Speed";Expression={
            #use an Associators Of query to get the NIC
              $nic=Get-WmiObject -query "associators of {Win32_NetworkAdapterConfiguration.Index=$($_.index)}" -computername $computer
              $nic.Speed
              }}
        } #close Try
        Catch
        {
            Write-Warning "Failed to retrieve IP configuration from $($computer.ToUpper())"
            Write-Warning $_.Exception.Message

        } #close Catch
    } #close ForEach
 } #close Process
} #end function

The function takes computernames as a parameter, uses WMI to get the NetworkAdapterConfiguration for IP and DHCP enabled adapters.

Get-WMIObject -Class win32_networkadapterconfiguration -computername $Computer -Filter "IPEnabled='TRUE' AND DHCPEnabled='TRUE'" -ErrorAction "Stop"

The rest of the function simply selects key properties including another WMI query to get the associated adapater's speed. Because some items like IP address are stored as arrays, I use a hash table expression to return the first item only.

PS C:\> get-ipdata

Description    : Atheros AR8131 PCI-E Gigabit Ethernet Controller (NDIS 6.20)
DNSHostname    : SERENITY
IPAddress      : 172.16.10.124
SubnetMask     : 255.255.0.0
DefaultGateway : 172.16.10.254
DNSDomain      : jdhitsolutions.local
PrimaryDNS     : 172.16.10.1
DHCPServer     : 172.16.10.1
DHCPLease      : 3/10/2011 7:30:01 AM
DHCPExpires    : 3/13/2011 8:30:01 AM
DHCPTimeToLive : 2.22:43:15.9650056
MACAddress     : 00:26:9E:C7:09:76
Speed          : 1000000000

I started to do my usual code polishing but then I realized this might be a good exercise for you. The function works as is with some limited error handling in a Try/Catch block. But there are several areas for improvement or enhancement. You might want to:

  • Add support for alternate credentials
  • Add comment based help
  • Add support for running as a background job
  • Create a graphical, WinForm/WPF version
  • Add IPv6 information
  • Add the average ping response time
  • Add more adapter information

I'll leave the rest to you. This could be a nice warmup practice for the upcoming Scripting Games.

Download Get-IPData.ps1


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

10 thoughts on “Get IP Data”

  1. james O'Neill says:
    March 10, 2011 at 10:13 am

    You don’t need the loop, one of the neat things about GET-WMIObject is Computer name can be array of names.

    1. Jeffery Hicks says:
      March 10, 2011 at 10:17 am

      Guess I just have the habit so that I can either pipe names to the function

      “computer1″,”computer2″,”computer3” | Get-IPData

      Or pass them as a parameter value

      Get-IPData “computer1″,”computer2″,”computer3”

      But in this case, the ForEach loop is redundant.

  2. Jeffery Hicks says:
    March 10, 2011 at 10:22 am

    After testing, if I was only calling Get-WMIObject you are correct. But because I have other things going on like some Write-Verbose messages, those fail so I need the ForEach loop.

  3. Jim says:
    March 10, 2011 at 12:33 pm

    !. Does NOT require Admin credentaials.
    2. Will NOT work for adapters with static addresses.

    Nice utility for gathering NIC data.

  4. Jim says:
    March 10, 2011 at 12:38 pm

    Sorry I should have said that
    1. Does NOT require admin credentials fo LOCAL machine.

  5. Koen says:
    March 10, 2011 at 6:05 pm

    I’m getting this error:

    WARNING: A positional parameter cannot be found that accepts argument ‘System.Object[]’.

    1. Jeffery Hicks says:
      March 10, 2011 at 6:06 pm

      That’s odd. What is the command you are trying to run?

      1. Vincent says:
        March 31, 2011 at 4:11 am

        Hi,

        The error is because there’s a small error on line 19. You’ve written “Select Description,DNSHostname” twice in a row.
        It works brilliantly if you remove the second one.

        Regards, Vincent

  6. Jeffery Hicks says:
    March 31, 2011 at 7:52 am

    Good eyes. That mistake was only in the posted code. It is not in the script text file you download. You have to be careful copying and pasting code samples which is why I always include a text file you can download. The function continues to work for me.

    1. Vincent says:
      April 1, 2011 at 9:19 am

      Yeah you’re right. The download link is a welcome change to most script sites. But because of that I still have the subconscious habit to copy on the site itself.

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d