首页 > 解决方案 > 使用 PowerShell 以字符串格式更改 IP 的第三个八位字节

问题描述

认为我找到了最糟糕的方法:

$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。

标签: regexstringpowershellconcatenation

解决方案


使用您的示例来了解如何修改第三个八位字节,我会以几乎相同的方式进行操作,但我会将一些步骤压缩在一起:

$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

推荐阅读