从行输出powershell中删除单词

时间:2017-11-03 10:38:09

标签: powershell

我有一个带有以下输出的powershell命令,命令输出显示每台机器的活动NIC适配器和NIC适配器名称不同。但我在这里看到的是,在一个服务器中,活动NIC适配器是本地连接,而在另一个服务器中,它是以太网。这将在所有VM中有所不同

PS C:\> netsh interface ipv4 show interface |where { $_ -match '\sconnected' -and $_ -notmatch 'loopback'}
     12           5        1500  connected     **Local Area Connection**
    PS C:\>
    PS C:\> netsh interface ipv4 show interface |where { $_ -match '\sconnected' -and $_ -notmatch 'loopback'}
     12           5        1500  connected     **Ethernet**
    PS C:\>

我只想捕获适配器名称(例如:Local Area Connection \ Ethernet等)。

任何人都可以帮我修改命令,这样我就可以获得没有任何空格作为输出的NIC适配器名称吗?

输出应如下所示

Local Area Connection
Ethernet
Ethernet 2 

1 个答案:

答案 0 :(得分:0)

如果您在Windows 8或Server 2012或更高版本的操作系统上运行此操作,则可以使用Get-NetAdapter cmdlet来获得所需的结果:

Get-NetAdapter | Where {$_.Status -eq 'Up'} | Select -ExpandProperty Name

在较旧的操作系统上,你可以试试这个,它将每个界面的文字分成单词" connected"并使用正则表达式特殊字符\s跟踪空格,然后返回该分割的第二项:

$Interfaces = netsh interface ipv4 show interface | where { $_ -match '\sconnected' -and $_ -notmatch 'loopback'}

$Interfaces | ForEach-Object { 
    ($_ -Split 'connected\s+')[1]
}

或者这是另一个选项,可以避免使用-split运算符,而是使用正则表达式lookbehind匹配“已连接”'在我们想要返回之前,在字符串中跟着5个空格:

$Interfaces = netsh interface ipv4 show interface | where { $_ -notmatch 'loopback'}

$Interfaces | ForEach-Object { 
    [regex]::matches($_, '(?<=connected\s{5})(.*)').value
}
相关问题