Understanding 1).split(':')[1].trim()

Hi,

Can someone help me understand what is happening in this command please ?

I get the first part, find IPv4 in IPConfig the the select first IPv4 that is in the list, but what is happening here 1).split(‘:’)[1].trim() ? I want to be able to use these type of skills as i learn, but its confusing !

$ip = (ipconfig | findstr “IPv4” | select -First 1).split(‘:’)[1].trim()

Many thanks,

That’s quite a one-liner, but I think we can walk through it easily enough.

.Split() is a string method and is acting on the output of the pipeline in parentheses just before it. It takes a string and splits it up using a specified character as a delimiter, in this case a colon. After the split is done, you are left with a collection of strings instead of a single string:

PS C:\> (ipconfig | findstr "IPv4" | select -First 1).split(':')
   IPv4 Address. . . . . . . . . . .
 169.254.80.80

Now you have two strings in a collection but you are only interested in one of them, so we use the index (square brackets) operator to get the second string. Collections are zero-indexed so the first item is 0, the second is 1 and so on:

PS C:\> (ipconfig | findstr "IPv4" | select -First 1).split(':')[1]
 169.254.80.80

After that, the trim() method removes all the leading and trailing spaces from the string so you only have the IP address string remaining.

Thank you Matt, thats very helpful :slight_smile:

Alternatively, on newer Windows versions you can use the Get-NetIPConfiguration cmdlet to retrieve the same information.