如果我正确理解了新示例的问题,您想要解析文件并创建单个变量,每个变量都包含一个数组 ip IP 地址。
如果是这种情况,您可以这样做:
# loop through the file line-by-line
$result = switch -Regex -File 'D:\Test\thefile.txt' {
'#\sSYSTEM\s(\w+)' {
# start a new object, output the earlier object if available
if ($obj) { $obj }
$obj = [PsCustomObject]@{ 'System' = $Matches[1]; 'Ip' = @() }
}
'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' {
# looks like an IPv4 address. Add it to the Ip property array of the object
$obj.Ip += $_
}
default {}
}
现在你在 $result 中有一个数组 ob 对象:
System Ip
------ --
Y {192.168.1.7, 192.168.1.8, 192.168.1.9, 192.168.1.7...}
X {192.168.1.3, 192.168.1.4, 192.168.1.5, 192.168.1.6}
制作单独的变量很容易:
$ipX = ($result | Where-Object { $_.System -eq 'X' }).Ip
$ipY = ($result | Where-Object { $_.System -eq 'Y' }).Ip
$ipZ = ($result | Where-Object { $_.System -eq 'Z' }).Ip
您的示例有重复的 IP 地址。如果你不想要这些
$ipX = ($result | Where-Object { $_.System -eq 'X' }).Ip | Select-Object -Unique
(其他人也一样)