我想我找到了最糟糕的方法:
$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但最好的方法是什么呢?完成时必须是字符串。不用费心去验证它是合法的IP。
发布于 2019-02-27 17:00:10
使用您想要修改第三个八进制的例子,我也会这样做,但是我会将其中一些步骤压缩到一起:
$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发布于 2019-02-27 17:08:19
您可以简单地使用-replace运算符PowerShell和一个前瞻性模式。看下面的脚本
Set-StrictMode -Version "2.0"
$ErrorActionPreference="Stop"
cls
$ip1 = "192.168.13.123"
$tests=@("192.168.13.123" , "192.168.13.1" , "192.168.13.12")
foreach($test in $tests)
{
$patternRegex="\d{1,3}(?=\.\d{1,3}$)"
$newOctet="420"
$ipNew=$test -replace $patternRegex,$newOctet
$msg="OLD ip={0} NEW ip={1}" -f $test,$ipNew
Write-Host $msg
}这将产生以下结果:
OLD ip=192.168.13.123 NEW ip=192.168.420.123
OLD ip=192.168.13.1 NEW ip=192.168.420.1
OLD ip=192.168.13.12 NEW ip=192.168.420.12如何使用-replace运算符?
https://powershell.org/2013/08/regular-expressions-are-a-replaces-best-friend/
理解我使用的模式
(?=) in \d{1,3}(?=.\d{1,3}$)意味着向后看。
(?=.\d{1,3}$ in \d{1,3}(?=.\d{1,3}$)是指DOT和1-3位数字后面的任何内容.
前导\d{1,3}是专门匹配1-3位数的指令。
所有这些都用通俗易懂的英语“给我一个句点后面的1-3位数字和位于字符串右侧边界的1-3位数字”。
展望未来regex
校正
regex模式是向前看,而不是后面看。
发布于 2019-02-27 18:09:40
如果您有PowerShell Core (v6.1或更高版本),则可以将与脚本块E 212E 113-进行替换E 214
PS> '192.168.13.1' -replace '(?<=^(\d+\.){2})\d+', { 1 + $_.Value }
192.168.14.1消极的前瞻性断言(?<=^(\d+\.){2})匹配所有的东西,但不包括,第三个八进制-没有考虑它的整体匹配的一部分,以取代。- `(?<=...)` is the look-behind assertion, `\d+` matches one or more (`+`) digits (`\d`), `\.` a _literal_ `.`, and `{2}` matches the preceding subexpression (`(...)`) 2 times.
然后,\d+只匹配第三个八进制;因为没有更多匹配,所以字符串的其余部分(.和第四个八进制)将被保留。在替换脚本块({ ... })中,$_以[MatchInfo]实例的形式引用匹配结果;它的.Value是匹配的字符串,即可以添加1的第三个八进制。- Data type note: by using `1`, an implicit `[int]`, as the _LHS_, the RHS (the `.Value` _string_) is implicitly coerced to `[int]` (you may choose to use an explicit cast).在输出时,无论脚本块返回什么,都会自动强制返回到字符串。
如果您必须与PowerShell兼容,请考虑Jeff Zeitlin's helpful answer。
https://stackoverflow.com/questions/54910282
复制相似问题