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

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…

192.168.10.0/24

192.168.13.0/24

192.168.20.0/24

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 !

 

 

 

Hello,
Here is one way to skin this cat…

$cidr = '192.168.10.0/24'
# 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.

HTH,
Steve