使用拆分找到匹配后选择下一行

时间:2017-10-02 14:55:18

标签: powershell text-parsing

感谢阅读。

我在一个小的PowerShell脚本中工作..想法是解析这个信息

      Hostname:
    xxxxx-CS0,xxxx
    Network:
    IPv4 Address            = xxxxx
    IPv4 Netmask            = 255.255.254.0
    IPv4 Gateway            = xxxxx
    DNS Servers             = xxxxx
Hostname:
xxxxx,8.1.9-184
Network:
IPv4 Address            = xxxxx
IPv4 Netmask            = xxxxx
IPv4 Gateway            = xxxxxx
DNS Servers             = xxxxxx
Hostname:
xxxxxx,7.1.80-7
Network:
IPv4 Address            = xxxx
IPv4 Netmask            = xxxxx
IPv4 Gateway            = xxxxx
DNS Servers             = xxxxx

所以......我已经获得了所有信息,除非带有此代码的主机名

  $info = Get-Content C:\xxxxxx\IP_info_all.txt

 write-host "Network Information VNX"



   ForEach ($network in $info)  {


   $hostname = ($network -split "`n")
   if($hostname -match "Hostname")
   {
   Write-Host $hostname
   $hostname =""
   }


     $b = ($network -split " ")[1]
     if ($b -match "Address") {
        $b
        $c = ($network -split "=")[1]
        $c
      if  ($name -match "IPv4"){
    $name
    $copyname =($network -split ":")[0]
     }
      }


     $b = ($network -split " ")[1]
     if ($b -match "Netmask") {
        $b 
         $maskid = ($network -split "=")[1]
         $maskid }

    $d = ($network -split " ")[1]
    if ($d -match "Gateway") {
            $d
     $Gatewayid = ($network -split "=")[1]
     $Gatewayid
     }


     $z = ($network -split " ")[1]
     $v = "DNS"
     if ($z -match "Servers") 
     {
     $v 
     $dnsserverid = ($network -split "=")[1,2,3]
     $dnsserverid
     }

输出给出了网络信息的名称和编号,但我不知道如何获得“Hostname”字符串下的下一行。

我需要这样输出:

Network Information VNX
Hostname:
Address
 xxxx
Netmask
 xxxx
Gateway
 xxxx
DNS
 xxxx
Hostname:

Address
 xxxx
Netmask
 xxxx

谢谢!

1 个答案:

答案 0 :(得分:0)

遍历每一行。在设置条件语句时,将1添加到符号化我想要读取下一行...

$info = Get-Content "C:\xxxxxx\IP_info_all.txt"
    write-host "Network Information VNX"
$content = ($info -split "`n") 

For($i=0;$i -lt $content.count;$i++){

    if($content[$i] -match "Hostname:")
    {
        "Hostname"
        Write-Host $content[$i+1]
    }
    elseif($content[$i] -match "Network:")
    {
        "Network"
        Write-Host ($content[$i]  -split "=")[1]
    }
    elseif($content[$i] -match "IPv4 Address")
    {
        "Address"
        Write-Host ($content[$i]  -split "=")[1]
    }
    elseif($content[$i] -match "IPv4 Netmask")
    {
        "Netmask"
        Write-Host ($content[$i] -split "=")[1]
    }
    elseif($content[$i] -match "IPv4 Gateway")
    {
        "Gateway"
        Write-Host ($content[$i] -split "=")[1]
    }
    elseif($content[$i] -match "DNS Servers")
    {
        "DNS Servers"
        Write-Host ($content[$i] -split "=")[1]
    }
}