O R G A N I C / F E R T I L I Z E R: how to retrieve your ip address with powershell...

Apr 1, 2008

how to retrieve your ip address with powershell...

update: this is how it’s performed in powershell v3 as demonstrated here.

(get-netadapter | get-netipaddress | ? addressfamily -eq 'IPv4').ipaddress

 

update: this is by far the easiest.

PS C:\temp> (gwmi Win32_NetworkAdapterConfiguration | ? { $_.IPAddress -ne $null }).ipaddress
192.168.1.101

 

 

are you laughing yet?  i know you probably find this topic amusing.  it's really interesting though.  whenever you get over it, i'll do this in the standard cmd.exe interpreter and then in powershell to show you what kind of coolness powershell does.

done?  okay, good.  this is an interpretation of a demo that bob wells did at our smug meeting.  hope you like it.

i should tell you, it's not as simple as the title would lead you to believe.  i like doing that little slight-of-hand thing since it gives the impression that i'm painting a very easy target on my back for your criticism (though it's probably true in other ways)!  the idea is that we want to retrieve just the ip address.  so here we go...

first of all, let's see how you'd get an ip address out of ipconfig.  since i can't get bob's method of regular expression to work, i created my own for this simple, little demo.  following is a series of commands and results to get to the final product. 

to start with, let's get the results of ipconfig and use findstr to pull out any lines that look like an ip address:

C:\temp>ipconfig | findstr [0-9].\.

   IPv4 Address. . . . . . . . . . . : 192.168.1.101
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1


alrighty, now we have a preliminary list of the addresses we want to use.  problem is, we need to strip it down to only the ip address, getting rid of the subnet mask and default gateway.  we can achieve this by passing the echoed statement back through findstr looking for the word address.  something like this:
C:\temp>for /f "delims=" %a in ('ipconfig ^| findstr [0-9].\.') do @echo %a | findstr "Address"

   IPv4 Address. . . . . . . . . . . : 192.168.1.101


so far, so good.  now let's get the ip address only.  we take the stuff from before and use it to the for command again to split everything with the delimiter ":", which gives us two tokens.  echoing the second one, we get the ip address:
C:\temp>for /f "delims=" %a in ('ipconfig ^| findstr [0-9].\.') do @for /f "tokens=1,2 delims=:" %i in ('@echo %a ^| findstr "Address"') do @echo %j

 192.168.1.101



ah crap!  see that?  there's a space we have to deal with!  to get rid of it, we'll pass it yet again through a for loop.  you see, the default delimiter of a for loop command is space and tab.  when we pass it back through, we just echo it back:

C:\temp>for /f "delims=" %a in ('ipconfig ^| findstr [0-9].\.') do @for /f "tokens=1,2 delims=:" %i in ('@echo %a ^| findstr "Address"') do @for /f %o in ('@echo %j') do @echo %o

192.168.1.101

 

and finally... we arrive at the results we were hoping for.  finally.

 

okay, let's do the same thing in powershell this time.  maybe we'll find it a little easier...

PS C:\temp> ipconfig | findstr [0-9].\.

   IPv4 Address. . . . . . . . . . . : 192.168.1.101
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1

 

so far the results look about the same.  unlike cmd.exe we're not just pushing around text.  in this case, the data is coming back as a string object.  when we run this through powershell, we can actually pull stuff out based on the index of the array.  since we know address is first, we can just call 0 like this:

PS C:\temp> (ipconfig | findstr [0-9].\.)[0]

   IPv4 Address. . . . . . . . . . . : 192.168.1.101

 

hmmm.  that was easy, but we're not done yet.  from here, we need to just retrieve the ip address.  the easiest way to do this is to split the contents (truncated it):

PS C:\temp> ((ipconfig | findstr [0-9].\.)[0]).Split()

IPv4
Address.
.
.
.
:
192.168.1.101

 

output is pretty ugly in that format, isn't it?  luckily, all we need is the last value.  just as 0 is the index which indicates the first member of an array, we can use -1 to indicate the very last one.  in this case, the split function moves the ip address to the very end.  now we can capture that array member and bring it back.  check it out:

PS C:\temp> ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

192.168.1.101

 

isn't that cool?

 

here's a couple of other things that bob demonstrated.  i'm sure you can figure them out on your own though.  no point in be boring you with my narrative:

[MATH]::Round(((Get-WmiObject win32_computersystem).totalphysicalmemory / 1gb),2)

foreach($file in Get-ChildItem){$size =+ $file.length}

12 comments:

  1. This works great for XP, but breaks down when you add Vista clients as they have IPv6 enabled. We end up with two lines, 1 the first two bytes of the v6 address (delimited by :) then the v4 address. I can't seem to tweak it to only display the v4 address for both XP & Vista.

    ReplyDelete
  2. hey man, give this a try instead... i did this on vista, but i don't have ipv6 enabled so i didn't run into the same issues as you describe. at any rate, i modified the regex statement which brings back a value without using an array so the [0] wasn't necessary anymore. here it is:

    (ipconfig | findstr .*IPv4.*[0-9].\.).Split()[-1]

    ReplyDelete
  3. oh, one more thing... here is the equivalent in for loop. i removed the complexity of passing through two for loops and just used token placement to find the exact location:

    for /f "tokens=13,14" %a in ('ipconfig ^| findstr .*IPv4.*[0-9].\.') do @echo %b

    ReplyDelete
  4. Thank you very much for posting; I needed just this Powershell command for a college assignment!

    ReplyDelete
  5. For some reason this doesn't seem to work on Win 7 with multiple active adapters (such as having VMWare Workstation on your machine). At that point all that in returned is the next command line. If I strip the .ipaddress off the end I can see information from each adapter.

    Also - if I do this command on a machine with a single adapter I get both the ipv4 and the ipv6 address - what if I need to reference just the ipv4 address?

    ReplyDelete
  6. This works for me for getting the IP address of the first active interface on Windows XP, unlike the line at the top of the post:

    (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .)[0].IPAddress

    ReplyDelete
  7. Windows 7 IPv4 only.

    (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE) | %{$_.ipaddress[0]}

    ReplyDelete
  8. Actually the [0] part at the end is sooo evil. If your intent (albeit missled) is to get the ipv4 address only, add this to the pipeline instead
    | ? {$_ -notlike "*:*}
    which excludes anything that looks like a ipv6

    ReplyDelete
    Replies
    1. for what matter, you could exclude based on a regex match since ipv4 will never contain alpha characters... hmmm.

      Delete
  9. created my own version based on the author's initial writeup, input from marcus on using IPv4 in the search string and my own need to list multiple IPs assigned to the same machine:

    ipconfig | findstr .*IPv4.*[0-9].\. | % { $_.split()[-1] }

    ReplyDelete
  10. Thanks for the blog posting. The below worked for me on Windows 7.

    Getting the IPv4 address on the last entry in the DNS listing:

    (gwmi win32_networkadapterconfiguration | ? {$_.IPAddress -ne $null})[-1].ipaddress[0]

    ...and the IPv6 version for the same DNS entry:

    (gwmi win32_networkadapterconfiguration | ? {$_.IPAddress -ne $null})[-1].ipaddress[1]

    ReplyDelete
  11. I want to apologize in advanced…im new to this: Lets say i wanted to pull the subnet out of the IP address using []. How do i set it to read the “.” as the separator instead of a Space? For ex if i do $nic.ipaddress[2] it will pull the 3rd set of numbers instead of the 3rd character?

    ReplyDelete