Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change 3rd octet of IP in string format using PowerShell

Think I've found the worst way to do this:

$ip = "192.168.13.1"
$a,$b,$c,$d = $ip.Split(".")
[int]$c = $c
$c = $c+1
[string]$c = $c
$newIP = $a+"."+$b+"."+$c+"."+$d

$newIP

But what is the best way? Has to be string when completed. Not bothered about validating its a legit IP.

like image 668
Guy Wood Avatar asked Jan 27 '23 16:01

Guy Wood


1 Answers

Using your example for how you want to modify the third octet, I'd do it pretty much the same way, but I'd compress some of the steps together:

$IP = "192.168.13.1"
$octets = $IP.Split(".")                        # or $octets = $IP -split "\."
$octets[2] = [string]([int]$octets[2] + 1)      # or other manipulation of the third octet
$newIP = $octets -join "."

$newIP
like image 136
Jeff Zeitlin Avatar answered Jan 30 '23 21:01

Jeff Zeitlin