【问题标题】:removing words from a line output powershell从行输出powershell中删除单词
【发布时间】:2017-11-03 19:44:00
【问题描述】:

我有一个带有以下输出的 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:\>

我只想捕获适配器名称(例如:本地连接\以太网等)。

谁能帮我修改命令,以便我得到没有任何空格的 NIC 适配器名称作为输出?

输出应该如下所示

Local Area Connection
Ethernet
Ethernet 2 

【问题讨论】:

    标签: powershell


    【解决方案1】:

    如果您在 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 运算符,而是使用正则表达式后向匹配 'connected' 后跟字符串中的 5 个空格,然后再返回:

    $Interfaces = netsh interface ipv4 show interface | where { $_ -notmatch 'loopback'}
    
    $Interfaces | ForEach-Object { 
        [regex]::matches($_, '(?<=connected\s{5})(.*)').value
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多