manipulating a line (IP) of a CSV to only use first 3 octets

Welcome Forums General PowerShell Q&A manipulating a line (IP) of a CSV to only use first 3 octets

This topic contains 1 reply, has 2 voices, and was last updated by

2 months, 2 weeks ago.

  • Author
  • #168760

    Topics: 1
    Replies: 0
    Points: 11
    Rank: Member

    I have a CSV file that is sent to me (lets say it is called NetInput.csv).  Each line is a subnet in CIDR format and appears like this example here...

    I am writing a ping sweep script using the following powershell one-liner that I will foreach through each subnet

    1..254 | % {"$first3octet.$($_): $(Test-Connection -count 1 -comp $first3octet.$($_) -quiet)"} | Out-File -FilePath C:\temp\pingtest.txt

    How would I take the first 3 octets of each line and put them in to a variable (the variable being $first3octet  in the line above).  essentially stripping off the .0/24 portion.

    I am pretty sure I would need to do something like

    # get the content of the csv

    $netlist = gc c:\temp\NetInput.csv

    # then do a 'foreach'  to each line of the file with some command to only use the first 3 octets in to a new variable

    foreach ($subnet in $netlist) {do something here that drops the .0/24 from the subnet and put in to $first3octet variable}

    Any help or suggestions would be greatly appreciated.  I am very new to powershell and eager to put it to good use !




  • #168802

    Topics: 14
    Replies: 43
    Points: 146
    Helping Hand
    Rank: Participant

    Here is one way to skin this cat..

    $cidr = ''
    # split the network ip on '.', select the first 3 items in the result object and join them back together with a '.' delimiter
    $First3Octets = ($cidr -split [regex]::Escape('.') | Select-Object -First 3) -join '.'

    Also, for future posts, it helps when you format the code in your post. Makes it easier to read.


You must be logged in to reply to this topic.