2017-09-17 46 views
0

我来自PERL背景,PowerShell只是让我困惑。我有一个开关配置,我试图确定一个配置是否存在,当它不应该。如何在数组中动态存储Select-String匹配Powershell

短例如:

//BAD interface has maximum of 2 but Only 1 learned 
interface GigabitEthernet0/0 
switchport access vlan 2 
switchport mode access 
switchport port-security maximum 2 
switchport port-security mac-address sticky 
switchport port-security mac-address sticky 0050.7966.6800 
switchport port-security 
media-type rj45 
negotiation auto 
spanning-tree portfast edge 
! 
//GOOD default maximum is 1 
interface GigabitEthernet0/1 
switchport access vlan 2 
switchport mode access 
switchport port-security mac-address sticky 
switchport port-security mac-address sticky 0050.7966.6801 
switchport port-security 
media-type rj45 
negotiation auto 
spanning-tree portfast edge 

的 '//' 以上线不是在实际的文件。所以“配置块”将来自“^ interface .... until!”

这里是我到目前为止的代码。

$ints = [System.Collections.ArrayList]@() 
$file = Get-Content .\router.txt | Out-String 
$file | Select-String -Pattern "(?s)interface [etfg][^!]+!" -AllMatches | foreach {$ints.Add($_.Matches.Value)} 

我试图将所有配置块添加到列表中以便稍后遍历并找到“最大命令”。

但是上面的代码是不是我的期望:

$ints.Count 
1 

有没有更好的方式来存储所有的“选择字符串”的匹配到一个列表?

我的下一个步骤是:

foreach ($int in $ints) { 
if interface configuration contains shutdown, next iteration 
else 
if maximum \d is present, check if there are the same amount of 
mac-sticky commands, if it doesnt it's a violation and store 
it for writing a file later. 

我要去上放置的一切〜1000的配置文件

原代码“出字符串”

回答

0

运行此为1个字符串,而不是一个数组。所以,当我搜索匹配,这只是一个字符串值匹配的

下面的代码削减它

$file = Get-Content .\router.txt | Out-String 
$ints = $file | Select-String -Pattern "(?s)\ninterface [etfg][^!]+!" -AllMatches | foreach {$_.Matches.Value} 
foreach ($line in $ints.split("!")) { 
    if ($line -match 'maximum\s*([0-9]+)') { 
     $allowedMacs = $matches[1] 
     if ($allowedMacs -gt ($line | Select-String "sticky [\d\w]" -AllMatches).Matches.Count) { 
      write-host "Violation!" 
     } else { 
      write-host "No Violation!" 
     } 
    } 
}