[英]Verify blocks of text in a file with powershell
I have a folder full of Cisco configurations. 我有一个充满思科配置的文件夹。 I am having a difficult time trying to find a way to verify strings of commands that are in the configuration. 我正在努力寻找一种方法来验证配置中的命令字符串。
I have no problem with single line commands and am currently using the following for that with 100% success: 我对单行命令没有任何问题,目前正在使用以下内容获得100%成功:
Get-childitem -path $Path -recurse |foreach-object{if (-not (select-string -inputobject $_ -Pattern "banner login")){$_}} | select name | Out-file $OutPath\OutputName.txt
I would like to verify commands such as this: 我想验证这样的命令:
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
The 4 lines will be the same through out all configurations. 在所有配置中,4条线将是相同的。 I have tried.. 我试过了..
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
...but that only checks for each of those commands separately and reports all configuration files as compliant. ...但是它只分别检查每个命令并报告所有配置文件是否合规。 I am trying to verify that specific block in that exact order. 我试图按照确切的顺序验证特定块。 Thank you for your time. 感谢您的时间。
Use a -match
, similar to this . 使用-match
,类似于此 。
Declare your search string outside that long line of code: 在那长串代码之外声明您的搜索字符串:
$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
"@
Apart from formatting, the only change is the Select-String
to -match
: 除格式化外,唯一的变化是Select-String
to -match
:
Get-childitem -path $Path -recurse | foreach-object {
If (-not (([IO.File]::ReadAllText($_.FullName)) -match ".*$str.*")) {
$_
}
} | Select Name | Out-file $OutPath\OutputText.txt
This will preserve order and take care of whitespace/newlines: 这将保留顺序并处理空格/换行符:
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.