首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在数组Powershell中动态存储选择字符串匹配

如何在数组Powershell中动态存储选择字符串匹配
EN

Stack Overflow用户
提问于 2017-09-17 05:06:20
回答 1查看 732关注 0票数 0

我来自PERL背景,PowerShell只是把我搞糊涂了。我有一个开关配置,我试图确定配置是否在不应该出现的时候出现。

简短的例子:

代码语言:javascript
复制
//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.直到!“

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

代码语言:javascript
复制
$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命令“。

然而,上面的代码并不是我所期望的:

代码语言:javascript
复制
$ints.Count
1

是否有更好的方法将所有的“选择字符串”匹配存储到列表中?

我的下一步是:

代码语言:javascript
复制
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个配置文件上运行这个

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-18 20:01:50

在最初的代码中,"out- string“将所有内容放入一个字符串中,而不是一个数组。所以当我搜索匹配时,只有一串匹配值。

下面的代码将其剪切

代码语言:javascript
复制
$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!"
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46260862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档