Reputation: 3
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".
Upvotes: 0
Views: 1181
Reputation: 3043
Creating a Synthetic Method for an IPAddress Object , a fun way of doing this...
$Method = {
Param(
[Int]$Number,
[ValidateSet(1,2,3,4)]
[Int]$Position
)
$OctetPosition = $Position - 1
$CurrentIpAddress = New-Object -TypeName System.Collections.ArrayList
$This.IpAddressToString -Split '\.' | ForEach-Object -Process {
$CurrentIpAddress.Add($_) | Out-Null
}
$ChangedOctet = [Int]($CurrentIpAddress[$OctetPosition]) + $Number
if( $ChangedOctet -gt 255 ){
throw "Resulting octet is $ChangedOctet which is greater than 255"
}
$CurrentIpAddress.Item($OctetPosition) = $ChangedOctet
return ($CurrentIpAddress -join '.')
}
$IPAddress = [System.Net.IpAddress]'192.168.1.1'
$IPAddress | Add-Member -MemberType ScriptMethod -Name Add -Value $Method
#$IPaddress.Add($Number,$OctetPosition)
$IPAddress.Add(200,4)
Upvotes: 0
Reputation: 17472
$IP_start = "192.168.1.1"
(($IP_start -split "\.")[0..2] -join ".") + ".200"
Upvotes: 1
Reputation: 1742
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
Upvotes: 2