Freigeben über


Simple Text Parse with Powershell using IPConfig.exe

Here is a fun little one-liner in Powershell:

PS C:\> ipconfig | where-object {$_ -match "IPv4 Address"}
IPv4 Address. . . . . . . . . . . : 1.2.3.4

This gets us just the lines from the IPConfig that list the IP address.  This isnt text parsing, this is just filtering the array of strings that came back from the IPConfig command.

Lets now start parsing this down.  Lets say first we want to see just the full IP Address.  There are many ways to do this, but I love the .Split() method of a string so I will start with that:

PS C:\> ipconfig | where-object {$_ –match “IPv4 Address”} | foreach-object{$_.Split(“:”)}
IPv4 Address. . . . . . . . . . .
1.2.3.4

So we have split the string and we see an array now.  Since this is a known string we can just go straight to the second item in the array:

PS C:\> ipconfig | where-object {$_ –match “IPv4 Address”} | foreach-object{$_.Split(“:”)[1]}
1.2.3.4

Its hard to see it on the blog here, but there is a space in front of the IP address.  we can get rid of that easily by using the .Trim() method:

PS C:\> ipconfig | where-object {$_ –match “IPv4 Address”} | foreach-object{$_.Split(“:”)[1].Trim()}
1.2.3.4

So you can see we have a simple one-liner that gets us any IP on this system by filtering and parsing the results of an IPConfig.  Now honestly there are probably better ways to get an IP Address, from the registry, from WMI.  This is mainly an example of text parsing.

You thought I was done…never… :)

So now that I see how simply I can chop down text like that, lets say maybe I am interested in that mighty third octet which on a very many networks is the subnet differentiator.  So I have come this far, now another simple split and call to an element of the array gets us the octet.:

PS C:\> ipconfig | where-object {$_ –match “IPv4 Address”} | foreach-object{$_.Split(“:”)[1].Trim().Split(".")[2]}
3

Very cool stuff…  Though remember, I said there are many ways to get this done.  If we knew from the beginning that we wanted the third octet there was a much simpler route to take:

PS C:\> ipconfig | where-object {$_ –match “IPv4 Address”} | foreach-object{$_.Split(“.")[-2]}
3

Dont forget when using arrays you can use negative numbers to call elements from the back.

 

This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm.

Comments

  • Anonymous
    July 09, 2014
    Very usefull, thanks !
  • Anonymous
    December 01, 2015
    Exactly what I was looking for!! :)