Skip to main content

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}

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
  12. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

using preloadpkgonsite.exe to stage compressed copies to child site distribution points

UPDATE: john marcum sent me a kind email to let me know about a problem he ran into with preloadpkgonsite.exe in the new SCCM Toolkit V2 where under certain conditions, packages will not uncompress.  if you are using the v2 toolkit, PLEASE read this blog post before proceeding.   here’s a scenario that came up on the mssms@lists.myitforum.com mailing list. when confronted with a situation of large packages and wan links, it’s generally best to get the data to the other location without going over the wire. in this case, 75gb. :/ the “how” you get the files there is really not the most important thing to worry about. once they’re there and moved to the appropriate location, preloadpkgonsite.exe is required to install the compressed source files. once done, a status message goes back to the parent server which should stop the upstream server from copying the package source files over the wan to the child site. anyway, if it’s a relatively small amount of packages, you can

How to Identify Applications Using Your Domain Controller

Problem Everyone has been through it. We've all had to retire or replace a domain controller at some point in our checkered collective experiences. While AD provides very intelligent high availability, some applications are just plain dumb. They do not observe site awareness or participate in locating a domain controller. All they want is the name or IP of one domain controller which gets hardcoded in a configuration file somewhere, deeply embedded in some file folder or setting that you are never going to find. How do you look at a DC and decide which applications might be doing it? Packet trace? Logs? Shut it down and wait for screaming? It seems very tedious and nearly impossible. Potential Solution Obviously I wouldn't even bother posting this if I hadn't run across something interesting. :) I ran across something in draftcalled Domain Controller Isolation. Since it's in draft, I don't know that it's published yet. HOWEVER, the concept is based off

sccm: content hash fails to match

back in 2008, I wrote up a little thing about how distribution manager fails to send a package to a distribution point . even though a lot of what I wrote that for was the failure of packages to get delivered to child sites, the result was pretty much the same. when the client tries to run the advertisement with an old package, the result was a failure because of content mismatch. I went through an ordeal recently capturing these exact kinds of failures and corrected quite a number of problems with these packages. the resulting blog post is my effort to capture how these problems were resolved. if nothing else, it's a basic checklist of things you can use.   DETECTION status messages take a look at your status messages. this has to be the easiest way to determine where these problems exist. unfortunately, it requires that a client is already experiencing problems. there are client logs you can examine as well such as cas, but I wasn't even sure I was going to have enough m