I am writing a powershell script that uses the ip address to generate the network address (10.12.142.12 to 10.12.142.0) All of the ip addresses that I will be handling follow the following format 10.xxx.xxx.12
I have tried using the String.Replace() method. It works until the ip address is something like the following 10.12.154.12 or 10.214.126.12. It grabs and replaces all the .12. Ive also tried some regex, but couldn't come up with an expression that matches only the last octet.
$ipAddress = "10.12.23.12"
$networkNumber = $ipAddress.replace(".12",".0")
I want 10.12.23.0, but I get 10.0.23.0
Either remove everything from the last . with String.Remove() and String.LastIndexOf(), then add .0:
$ipAddress = "10.12.23.12"
$network = $ipAddress.Remove($ipAddress.LastIndexOf('.')) + '.0'
or use a regular expression that only replace .12 at the end of the string:
$ipAddress = "10.12.23.12"
$network = $ipAddress -replace '\.\d{1,3}$','.0'
Both of these will work with any value in the last octet, not just .12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With