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

This topic contains 3 replies, has 3 voices, and was last updated by  Martin Nielsen 3 years, 4 months ago.

  • Author
  • #23414

    Graham Beer


    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,

  • #23417

    Matt McNabb

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

    [b].Split()[/b] 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. . . . . . . . . . .

    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]

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

  • #23423

    Graham Beer

    Thank you Matt, thats very helpful 🙂

  • #23443

    Martin Nielsen

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

You must be logged in to reply to this topic.