Powershell 从输出中提取价值

问题描述 投票:0回答:1

在 powershell 中,如何获取“名称”列下第一行的值

PS D:\Users\foo>  Get-NetAdapter -InterfaceIndex $(Get-NetConnectionProfile | ? IPv4Connectivity -eq "Internet").InterfaceIndex

Name          InterfaceDescription   ifIndex Status   MacAddress   LinkSpeed
----          --------------------   ------- ------   ----------   ---------
Ethernet 8    Foobar #2                    3 Up      zz-zz-zz-zz   5 Gbps

结果值为“Ethernet 8”

powershell
1个回答
2
投票

PowerShell-native 命令发出 objects,(通常)不仅仅是 text.

如果 for-display 输出显示列名如

Name
通常 暗示输出对象具有这样的属性(预定义 formatting data 可能会呈现 calculated 具有任意名称的属性值,但是)[1]:

(
  Get-NetAdapter -InterfaceIndex (
      Get-NetConnectionProfile | 
      ? IPv4Connectivity -eq Internet
    ).InterfaceIndex
)[0].Name
  • [0]
    选择由 Get-NetAdapter
     发出的 
    first

    输出对象
  • .Name
    返回该对象的
    Name
    属性值。

注:

  • 如果您的系统没有连接互联网的适配器,则上述命令将失败,因为将诸如
    [0]
    的索引应用于“无”(
    $null
    或产生无输出的命令)会导致
    Cannot index into a null array. 
    错误。

[1] 在 PowerShell 7.4+ 中,calculated 属性显示 italicized 以表明该事实。

© www.soinside.com 2019 - 2024. All rights reserved.