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

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Martin Nielsen Martin Nielsen 1 year, 8 months ago.

  • Author
    Posts
  • #23414
    Profile photo of Graham Beer
    Graham Beer
    Participant

    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,

  • #23417
    Profile photo of Matt McNabb
    Matt McNabb
    Participant

    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. . . . . . . . . . .
     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 [b]trim()[/b] method removes all the leading and trailing spaces from the string so you only have the IP address string remaining.

  • #23423
    Profile photo of Graham Beer
    Graham Beer
    Participant

    Thank you Matt, thats very helpful 🙂

  • #23443
    Profile photo of Martin Nielsen
    Martin Nielsen
    Participant

    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.