【发布时间】:2017-10-17 18:53:34
【问题描述】:
感谢阅读
我在一个小脚本中工作,它读取一个 txt 输出并解析信息,
这是用作示例的信息:
Hostname:
xxxx1-CS0,8.1.9-184
Network:
IPv4 Address = 1.1.1.1.1.1
IPv4 Netmask = 1.1.1.1.1.4
IPv4 Gateway = 1.1.1.1.1.5
DNS Servers = 1.1.1.1.1.1,1.1.1.1.1.12
Hostname:
xxxx2,7.1.80-7
Network:
IPv4 Address = 2.2.2.2.1
IPv4 Netmask = 2.2.2.2.3
IPv4 Gateway = 2.2.2.2.4
DNS Servers = 2.2.2.2.2,2.2.2.2.3
Hostname:
xxxxx3,8.1.9-184
Network:
IPv4 Address = 3.3.3.3.3.1
IPv4 Netmask = 3.3.3.3.3.2
IPv4 Gateway = 3.3.3.3.3.5
DNS Servers = 3.3.3.3.3.3,3.3.3.3.3.4
Hostname:
xxxx4,8.1.9-184
Network:
IPv4 Address = 4.4.4.1
IPv4 Netmask = 4.4.4.2
IPv4 Gateway = 4.4.4.3
DNS Servers = 4.4.4.41,4.4.4.42
所以...这是我在堆栈的帮助下使用的代码
Clear-Host
$info = Get-Content xxxx
$finalpatch = "xxxx"
$content = ($info -split "`n")
For($i=0;$i -lt $content.count;$i++){
if($content[$i] -match "Hostname:")
{
#"Hostname Information"
$infohostname = $content[$i+1]
}
elseif($content[$i] -match "IPv4 Address")
{
#"Ipv4 Address"
$infoipv4 = ($content[$i] -split "=")[1]
}
elseif($content[$i] -match "IPv4 Netmask")
{
#"Netmask Information"
$infonetmask = ($content[$i] -split "=")[1]
}
elseif($content[$i] -match "IPv4 Gateway")
{
#"Gateway Information"
$gatewayinfo = ($content[$i] -split "=")[1]
}
if($content[$i] -match "DNS Servers")
{
# "DNS Servers Information"
$dnsinfo = ($content[$i] -split "=")[1]
}
Write-Host $infohostname ,$infoipv4,$infonetmask,$gatewayinfo,$dnsinfo
代码的结果是这样的:
xxxx1-CS0,8.1.9-184 4.4.4.1 4.4.4.2 4.4.4.3 4.4.4.41,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3
xxxxx3,8.1.9-184 2.2.2.2.1 2.2.2.2.3 2.2.2.2.4 2.2.2.2.2,2.2.2.2.3
xxxxx3,8.1.9-184 3.3.3.3.3.1 2.2.2.2.3 2.2.2.2.4 2.2.2.2.2,2.2.2.2.3
xxxxx3,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 2.2.2.2.4 2.2.2.2.2,2.2.2.2.3
xxxxx3,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 3.3.3.3.3.5 2.2.2.2.2,2.2.2.2.3
xxxxx3,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 4.4.4.1 3.3.3.3.3.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 4.4.4.1 4.4.4.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 4.4.4.1 4.4.4.2 4.4.4.3 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 4.4.4.1 4.4.4.2 4.4.4.3 4.4.4.41,4.4.4.42
这是为了解析行中的信息,但问题是计数的重复,我正在寻找一种方法来只获取每个设备的最后一行并解析数字,如果你看输出不要'不知道为什么数组会保留其他设备的 ip 地址,例如:
xxxx4,8.1.9-184 3.3.3.3.3.1 3.3.3.3.3.2 3.3.3.3.3.5 3.3.3.3.3.3,3.3.3.3.3.4
xxxx4,8.1.9-184 4.4.4.1 4.4.4.2 4.4.4.3 4.4.4.41,4.4.4.42
是相同的“主机名”信息,但第一行是从前一个设备获取 IP 地址。如果您查看示例,则每个设备的最后一行是正确的。
【问题讨论】:
标签: powershell parsing powershell-3.0 text-parsing