我来自PERL背景,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上面的'//‘行不在实际文件中。因此,"config块“将来自”^interface.直到!“
这是我到目前为止的代码。
$ints = [System.Collections.ArrayList]@()
$file = Get-Content .\router.txt | Out-String
$file | Select-String -Pattern "(?s)interface [etfg][^!]+!" -AllMatches | foreach {$ints.Add($_.Matches.Value)}我正在尝试将所有配置块添加到一个列表中,以便稍后迭代并找到"maximum命令“。
然而,上面的代码并不是我所期望的:
$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个配置文件上运行这个
发布于 2017-09-18 20:01:50
在最初的代码中,"out- string“将所有内容放入一个字符串中,而不是一个数组。所以当我搜索匹配时,只有一串匹配值。
下面的代码将其剪切
$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!"
}
}
}https://stackoverflow.com/questions/46260862
复制相似问题