read section of lines from Cisco IOS configuration loaded as text file in powershell

萝らか妹 提交于 2019-11-28 14:46:52

One way to do this is to use a state variable and an appropriate regular expression. Here's an example function:

function Get-Section {
  param(
    [String[]] $configData,
    [String] $sectionName
  )
  $pattern = '(?:^(!)\s*$)|(?:^[\s]+(.+)$)'
  $inSection = $false
  foreach ( $line in $configData ) {
    # Skip empty lines
    if ( $line -match '^\s*$' ) {
      continue
    }
    if ( $line -eq $sectionName ) {
      $inSection = $true
      continue
    }
    if ( $inSection ) {
      if ( $line -match $pattern ) {
        [Regex]::Matches($line, $pattern) | ForEach-Object {
          if ( $_.Groups[1].Success ) {
            $_.Groups[1].Value
          }
          else {
            $_.Groups[2].Value
          }
        }
      }
      else {
        $inSection = $false
      }
      if ( -not $inSection ) {
        break
      }
    }
  }
}

If your example data is in a text file (e.g., config.txt), you could extract the interface GigabitEthernet0/1 section as follows:

$configData = Get-Content "config.txt"
Get-Section $configData 'interface GigabitEthernet0/1'

The output would be:

description YYY
speed 1000
duplex full
nameif YYY
security-level 100
ip address 2.2.2.2 255.255.255.0
!

The function doesn't output the section's name because you already know it (you passed it to the function).

If you know the number of lines following the APP_GROUP, which in this case is 3, you can use that value for the -Context switch on Select-String:

$config | Select-String -Pattern '(object-group network APP_GROUP)' -Context 0,3

Which would give:

object-group network APP_GROUP
   network-object host 10.10.20.1
   network-object host 10.10.20.2
   network-object host 10.10.20.3

Edit: Alternative regex solution below since no of lines is dynamic

$section = 'APP_GROUP'
$regex = "(?:object-group\snetwork\s$section\n)(\snetwork-object\shost\s.*\n)+(?=object-group)"

$oneline = Get-Content C:\temp\cisco.txt | Out-String
$oneline -match $regex 
$matches[0]

network-object host 10.10.20.1
network-object host 10.10.20.2
network-object host 10.10.20.3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!