使用powershell

时间:2016-04-28 23:53:10

标签: powershell

我有一个充满思科配置的文件夹。我正在努力寻找一种方法来验证配置中的命令字符串。

我对单行命令没有任何问题,目前我正在使用以下内容,并取得100%的成功:

Get-childitem -path $Path -recurse |foreach-object{if (-not (select-string -inputobject $_ -Pattern "banner login")){$_}} | select name | Out-file $OutPath\OutputName.txt

我想验证这样的命令:

    access-list 69 remark Name
    access-list 69 permit x.x.x.x
    access-list 69 permit x.x.x.x
    access-list 69 permit x.x.x.x

在所有配置中,4条线将是相同的。我试过..

    Get-childitem -path $Path -recurse |foreach-object{if (-not (select-string -inputobject $_ -Pattern "access-list 69 remark Name", "access-class xx in", "access-list 69 permit x.x.x.x", "access-list 69 permit x.x.x.x", "access-list 69 permit x.x.x.x")){$_}} | select name | Out-file $OutPath\OutputText.txt

...但是它只分别检查每个命令并报告所有配置文件是否合规。我试图按照确切的顺序验证特定块。谢谢你的时间。

2 个答案:

答案 0 :(得分:2)

使用-match,类似于this

在那长串代码之外声明你的搜索字符串:

$str = @"
access-list 69 remark Name
access-list 69 permit x.x.x.x
access-list 69 permit x.x.x.x
access-list 69 permit x.x.x.x
"@

除格式外,唯一的变化是Select-String-match

Get-childitem -path $Path -recurse | foreach-object {
   If (-not (([IO.File]::ReadAllText($_.FullName)) -match ".*$str.*")) {
      $_
   }
} | Select Name | Out-file $OutPath\OutputText.txt

答案 1 :(得分:2)

这将保留顺序并处理空格/换行符:

$CfgBlock = @(
    'access-list 69 remark Name',
    'access-class xx in',
    'access-list 69 permit x.x.x.x',
    'access-list 69 permit x.x.x.x',
    'access-list 69 permit x.x.x.x'
) 

$CfgRegex = '\s*' + (($CfgBlock -split '\s+' | ForEach-Object {[regex]::Escape($_)}) -join '\s+') + '\s*'

Get-ChildItem -Path $Path -Recurse | Where-Object {
    (Get-Content -Path $_.FullName -Raw) -notmatch $CfgRegex
} | Select-Object -Property Name | Out-file $OutPath\OutputText.txt