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".
$First.LastIndexOf('.')
on its own? I cannot reproduce your issue so something is different. LastIndex of will return -1 if it did not find anything so that would cause the issue. You tell us what $first is but we have to guess how you populated it. In either case I would say use the[ipaddress]
type to help with this stackoverflow.com/questions/30061062/… – Matt