如何用PowerShell与Regex仅匹配running-config的首个line vty条目
Solution to Extract First Line VTY from Running-Config
Hey there! The issue with your current script is that it scans the entire config file—including both running and startup sections—so it picks up all 4 line VTY entries. To target just the first one from the running-config section, we can adjust the script to isolate that section first before searching.
Here's the modified PowerShell script that does exactly what you need:
# Read the entire config file as a single string (makes section splitting easier) $configContent = Get-Content -Path c:\test\config.txt -Raw # Extract only the running-config section (everything between "show running-config" and "start-up config") $runningConfigSection = ($configContent -split 'start-up config')[0] -replace '^show running-config\s*', '' # Find the first line vty entry along with its 6 lines of context, then keep only the first match $firstRunningVTY = Select-String -InputObject $runningConfigSection -Pattern "\sline\svty\s\d{1}\s\d{1,2}" -Context 0,6 | Select-Object -First 1 # Output the result Write-Host $firstRunningVTY
Let's break down what each part does:
Get-Content -Raw: Reads the entire file into one string instead of separate lines, which simplifies splitting the config into sections.- Splitting the config: We split the content at the "start-up config" marker to grab everything before it (the running-config section), then remove the "show running-config" header using
-replace. Select-Object -First 1: Ensures we only capture the first matching line VTY entry from the isolated running-config section.
Optional tweak: If your config might have multiple spaces between keywords (instead of single spaces), adjust the pattern to "\s*line\s+vty\s+\d+\s+\d+" to handle variable spacing.
内容的提问来源于stack exchange,提问作者CBLT
相关产品推荐
相关产品推荐

