【问题标题】:Selecting index of an array from a cmdlet [duplicate]从 cmdlet 中选择数组的索引 [重复]
【发布时间】:2015-11-17 23:58:01
【问题描述】:

我正在尝试获取我的本地 IP 地址:

gwmi Win32_NetworkAdapterConfiguration | Select Description,IPAddress | ?{$_.IPAddress -ne $null}

现在,这给了我适配器的描述(名称),以及字符串数组中的 IPv4 地址和 IPv6 地址。我将如何在 Select-cmdlet 中仅选择 IPv4 地址?我尝试了多种方法,但似乎找不到解决方案。

谢谢!

【问题讨论】:

  • 要修改您现在拥有的语法,这里有一个解决方案。 gwmi Win32_NetworkAdapterConfiguration | ?{$_.IPAddress -ne $null} | Select Description,@{n='IPAddress';e={$_.IpAddress[0]}}
  • 嗯,很有趣。谢谢
  • 来自 Mathias:这将在只有 IPv6 地址的适配器上产生意想不到的结果
  • 这正是我所需要的。谢谢!

标签: powershell


【解决方案1】:

您可以将 -match 与匹配计算属性内的 IPv4 地址的正则表达式模式一起使用:

$IPv4Pattern = '^(\d{1,3}\.){3}\d{1,3}$'
gwmi Win32_NetworkAdapterConfiguration | Select Description,@{Name="IPAddress";Expr={$_.IPAddress|Where{ $_ -match $IPv4Pattern}}} | ?{$_.IPAddress -ne $null}

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2018-02-08
    • 2015-09-17
    相关资源
    最近更新 更多