Search code examples
powershellsubstringip-addresslastindexof

Substring IP-Address with adding a string generates error but works


I have following command:

$IP_start = $First.Substring(0, $First.LastIndexOf('.'))+ ".200"

$First is an IP-Address, for example 192.168.0.1

I want to change the 1 in the fourth octect into a 200.

Write-Output $IP_start

gives me the correct IP-Address 192.168.0.200, but at the same time I get the following Error:

Ausnahme beim Aufrufen von "Substring" mit 2 Argument(en): "Die Länge darf nicht kleiner als 0 (null) sein. Parametername: length" In *ps1:31 Zeichen:3 + $IP_start = $First.Substring(0, $First.LastIndexOf('.'))+ ".200" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentOutOfRangeException

English translation

Exception when calling "substring" with 2 arguments: "The length can not be less than zero. Parameter name: length" In * ps1: 31 characters: 3...

I think everything is working fine, but that error messages bothers me.

//edit:

There's an ip.txt, where each line is like "192.168.0.1; ABCDEF"

$txt = Get-Content ip.txt
$editline = foreach ($Data in $txt) {
  $First, $Second = $Data -split ';' -replace '^\s*|\s*$'

$IP_start = $First.Substring(0, $First.LastIndexOf('.'))+ ".200"
Write-Output "modify ipaddr_first $IP_start"
}

$editline | Out-File "$output"

$first is therefore "192.168.0.1" and $second is "ABCDEF".


Solution

  • You can use regular expressions

    $IP_start = "192.168.1.1"
    $IP_start -replace "\d{1,3}$","200"
    

    This will change any 192.168.1.xxx by 192.168.1.200