powershell - 如何过滤powershell ssh输出
问题描述
我使用PowerShell 中描述的脚本,读/写 SSH.NET 流以从我的防火墙获取信息。但是我只需要隔离 4 个值。
编辑“ test-connection1 ”
设置vdom“ test1 ”
设置ip 192.168.0.1 255.255.255.0
设置allowaccess ping
设置inbandwidth 10000
设置outbandwidth 10000
编辑“ test-connection2 ”
设置vdom“ test1 ”
设置ip 192.168.1.1 255.255.255.0
设置allowaccess ping
设置带宽10000
设置带宽10000
--
编辑“ test-connection3 ”
设置 vdom“ test2 ”
设置 ip 192.168.2.1 255.255.255。0
设置允许访问 ping
设置带宽10000
设置带宽10000
我只需要显示粗体值。每次“编辑”都需要创建新行。这些值可以用逗号分隔。
我需要得到以下结果
test-connection,test1,10000,10000
test-connection2,test1,10000,10000
test-connection3,test2,10000,10000
如何操作在函数中创建的输出
function ReadStream($reader)
{
$line = $reader.ReadLine();
while ($line -ne $null)
{
$line
$line = $reader.ReadLine()
}
}
解决方案
如果每次编辑都是可预测的,您可以执行以下操作:
switch -Regex -File edit.txt {
'^edit "(?<edit>[^"]+)"' {$edit = $matches.edit}
'^set vdom "(?<vdom>[^"]+)"' {$vdom = $matches.vdom}
'^set inbandwidth (?<inb>\d+)' {$inb = $matches.inb}
'^set outbandwidth (?<outb>\d+)' { $edit,$vdom,$inb,$matches.outb -join ","}
}
$matches
是一个自动变量,包含使用-match
运算符进行字符串比较的结果。每次成功匹配时都会覆盖该变量。可以使用成员访问运算符按名称访问捕获组值.
。这就是您看到$matches.edit
检索edit
捕获组值的语法的原因。
该switch
语句可以使用参数逐行读取文件-File
并使用参数执行正则表达式匹配-Regex
。
如果编辑条目的格式是可预测的,我们可以假设我们将始终按该顺序有一个edit
、vdom
、inbandwidth
和outbandwidth
行。这意味着我们可以假设我们将按该顺序进行匹配,因此edit
一旦匹配就可以输出所有块outbandwidth
匹配。
正则表达式(正则表达式)是每行单引号内的值。以下是使用的两种表达式的细分:
^edit "(?<edit>[^"]+)"
:
- ^ 在行首断言位置
- edit 匹配字符 edit 字面意思(不区分大小写)
- 命名捕获组编辑 (?[^"]+)
- 匹配列表 [^"]+ 中不存在的单个字符,这意味着不是双引号字符。
- 量词 (+) — 匹配一次到无限次,尽可能多次,根据需要回馈(贪婪)
- " 匹配字符 " 字面意思(区分大小写)
^set inbandwidth (?<inb>\d+)
:
- ^ 在行首断言位置
- set inbandwidth 匹配字符 set inbandwidth 字面意思(不区分大小写)
- 命名捕获组 inb (?\d+)
- \d+ 匹配一个数字(等于 [0-9])
- 量词 (+) — 匹配一次到无限次,尽可能多次,根据需要回馈(贪婪)
推荐阅读
- java - request.getParameter on
- sql-server - pyodbc 比直接 SQL 慢 3 倍
- python - 不同颜色的叠加图
- python - 在 Python3 中修改包含集合的集合列表
- swift - 如何在 Xcode 中从 IBaction 函数创建视图
- php - 当用户在表单中写一个数字时,如何给一个数字一个变量?
- python - 如何在 Frida 中使用 rpc 暴露?
- django - django 使用 slug 不是 pk
- firebase - “FirebaseAuthError:解码 Firebase ID 令牌失败” - 但令牌是正确的,它只发生在 Chrome 上
- sql - 在 SQL Server 中创建一个具有除少数表之外的所有权限的角色