我需要帮助,以使用Powershell和Regex

时间:2018-12-25 22:53:20

标签: regex powershell

我需要从线路交换端口主干本机VLAN 250捕获到末端!标记为“是”,然后编写另一种搜索模式以查找此接口中是否使用了任何访问端口

interface fa0/1
 switchport
 switchport trunk encapsulation dot1q
 switchport trunk native vlan 250
 switchport trunk allowed vlan 48-52,54,64,66,68,70,74,76,80,82,84,86,88,96,98
 switchport trunk allowed vlan add 104,106,112,128,144,148,150,178,182,184,186
 switchport trunk allowed vlan add 192,194,199,250
 switchport mode trunk
 switchport nonegotiate
 spanning-tree portfast trunk
!

我写了一个powershell函数,并在下面使用Regex语句查找任何找到的本地本地交换机端口vlan 1或其他。如果找到,那么我想确定是否在此界面中配置了切换端口模式访问。

$String="switchport\strunk\snative\svlan\s((?!1)|1)"

在powershell中,我写了

$Access_Port =  Select-String -Path $File -Pattern $String 

运行此代码,它找到了switchport干线本机vlan 1,但直到!才包含其余的行。标记。

2 个答案:

答案 0 :(得分:0)

以下正则表达式将捕获所有行:

switchport trunk native vlan 250((.*\n))+

我在https://regex101.com

中进行了测试

您可以使用以下正则表达式来匹配who 包含或不包含特定单词的行

^(?=.*?\bmust-have\b)(?=.*?\bmandatory\b)((?!avoid|illegal).)*$

您可以进一步参考:

https://www.regular-expressions.info/completelines.html

答案 1 :(得分:0)

您是否考虑过不使用正则表达式的解决方案?

$sr = New-Object System.IO.StringReader @'
interface fa0/1
 switchport
 switchport trunk encapsulation dot1q
 switchport trunk native vlan 250
 switchport trunk allowed vlan 48-52,54,64,66,68,70,74,76,80,82,84,86,88,96,98
 switchport trunk allowed vlan add 104,106,112,128,144,148,150,178,182,184,186
 switchport trunk allowed vlan add 192,194,199,250
 switchport mode trunk
 switchport nonegotiate
 spanning-tree portfast trunk
!
'@
while( ($s = $sr.ReadLine()) ) {
  if( $s.TrimStart().StartsWith('switchport trunk native vlan') ) {
    while( ($s = $sr.ReadLine()) -and $s.Trim() -ne '!' ) { 
      if( $s.TrimStart().StartsWith('switchport trunk allowed vlan') ) {
        $p = (-split $s)[-1] -split ','
        Write-Host '$p type is', $p.GetType().FullName, '; $p contains', $p.Length, "elements: ${p}"
      }
    }
  }
}
$sr.Dispose()

输出

$p type is System.String[] ; $p contains 15 elements: 48-52 54 64 66 68 70 74 76 80 82 84 86 88 96 98
$p type is System.String[] ; $p contains 11 elements: 104 106 112 128 144 148 150 178 182 184 186
$p type is System.String[] ; $p contains 4 elements: 192 194 199 250