字符串匹配但唯一之后选择5行

时间:2019-01-16 21:15:13

标签: powershell-v4.0

我想解析设备配置txt文件,并在匹配字符串后选择10行。该配置文件在配置中的不同位置配置了相同的接口,因此当我运行PowerShell脚本时,它发现两个发现了两个我不想要的重复接口。我只希望脚本仅返回唯一接口的输出。

$OSPF_Interfaces = Select-String -Path $File -Pattern "no\spassive-interface\s(Port-channel|TenGigabitEthernet|GigabitEthernet)" |
                   select -ExpandProperty line |
                   Select-Object -Unique

$Active_Interface = $OSPF_Interfaces -replace " no passive-interface ", "interface " |
                    Select-Object -Unique

$Active_Interface输出正确

interface GigabitEthernet1/1
interface GigabitEthernet1/2
interface GigabitEthernet1/3

所以现在我想解析配置文件以找到$Active_interface中每个接口的匹配项,并为每个接口选择2行匹配项:

foreach ($item in $Active_Interface) {
     $Authenticated_Interface = Select-String -Path $File -Pattern "^$item" -Context 0,2 |
                                Select -Unique
     $Authenticated_Interface
}

上面的代码可以正常工作,但返回的重复匹配如下:

interface GigabitEthernet1/1
description link to building 1
Medical
interface GigabitEthernet1/1
description link to building 1
Medical
interface GigabitEthernet1/2
description link to building 2
Garage
interface GigabitEthernet1/2
description link to building 2
Garage
interface GigabitEthernet1/3
description link to building 3
Gate
interface GigabitEthernet1/3
description link to building 3
Gate

我不希望重复,但我不知道如何使它仅返回一个唯一的记录,如下所示:

interface GigabitEthernet1/1
description link to building 1
Medical
interface GigabitEthernet1/2
description link to building 2
Garage
interface GigabitEthernet1/3
description link to building 3
Gate

0 个答案:

没有答案