Powershell和regex解析配置了ospf的配置和显示界面

时间:2019-03-08 04:25:31

标签: powershell

请帮助。我要显示输出

interface vlan1 is not configured with ospf
interface vlan3 is configured with ospf
interface vlan7 is configured with ospf

但是我在下面运行此脚本时得到的输出是

interface vlan1 interface vlan3 interface vlan7 is configured with ospf

$interface = select-string -path c:\doc\config.txt -pattern "interface\vlan\d{1,3} -context 0, 3

$ospf = Select-string -inputobject $interface -pattern "ip ospf message-digest.*" | % {$_.matches.value}
if ($ospf -ne $null)
{
   $int = $ interface | select -expandproperty line #don't want to show line#
   write-host "$int is configured with ospf"
}
else
  {
    $int = $ interface | select -expandproperty line #don't want to show line#
     Write-host "$int is not configured with ospf"
  }

interface Vlan1
 no ip address
 shutdown
!
interface Vlan3
 ip ospf message-digest-key 100 md5 7 aa93naf
!
interface Vlan7
 standby 38 preempt
 ip ospf message-digest-key 100 md5 7 asf9394

1 个答案:

答案 0 :(得分:0)

您的方法使IMO过于复杂

  1. 将配置文件拆分为由!分隔的块(接口),
  2. 检查每个单个接口的ospf字符串,
  3. 选择当前界面的第一行并输出测试结果。

## Q:\Test\2019\03\08\SO_55056710.ps1
$interfaces = (Get-Content .\config.txt -Raw) -split "!`r?`n"

foreach($interface in $interfaces){
    if ($interface -match "ip ospf message-digest"){
        $ospf = "is"} else {$ospf = "is not"}
    "{0} {1} configured with ospf" -f ($interface -split "`r?`n")[0],$ospf
}

示例输出:

> Q:\Test\2019\03\08\SO_55056710.ps1
interface Vlan1 is not configured with ospf
interface Vlan3 is configured with ospf
interface Vlan7 is configured with ospf