PowerShell相当于LINQ SelectMany方法

EMP*_*EMP 20 linq powershell

我正在编写PowerShell代码来获取所有本地IPv4地址,不包括环回地址.我需要类似LINQ SelectMany方法的东西,但我无法弄清楚如何用PS滤镜做到这一点.这是我到目前为止的代码,它使用一个普通的旧ArrayList:

function Get-Computer-IP-Address()
{
    $ipAddresses = New-Object System.Collections.ArrayList

    $networkAdaptersWithIp = Get-WmiObject Win32_NetworkAdapterConfiguration | ? { $_.IPAddress -ne $null }
    foreach ($networkAdapter in $networkAdaptersWithIp)
    {
        foreach ($ipAddress in $networkAdapter.IPAddress)
        {
            if ($ipAddress -notlike "127.*" -and $ipAddress -notlike "*::*")
            {
                $ipAddresses.Add($ipAddress)
            }
        }
    }

    if ($ipAddresses.Length -eq 0)
    {
        throw "Failed to find any non-loopback IPv4 addresses"
    }

    return $ipAddresses
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更简洁的方法,只需更少的代码.

ste*_*tej 21

如果你结合Foreach-ObjectWhere-Object喜欢这样你就可以做到:

$ipaddresses = @(
  Get-WmiObject Win32_NetworkAdapterConfiguration | 
  ? { $_.IPAddress -ne $null } |
  % { $_.IPAddress } |
  ? { $_ -notlike "127.*" -and $_ -notlike "*::*" })
Run Code Online (Sandbox Code Playgroud)

请注意@(...).这导致,如果管道内的结果是什么,空数组分配给$ipaddresses.

  • ?= where-object; %= foreach-object; (17认同)

Iva*_*rov 18

只是回答主题 "PowerShell相当于LINQ SelectMany方法"的问题:

collection.SelectMany(el => el.GetChildren()) // SelectMany in C#
Run Code Online (Sandbox Code Playgroud)

相当于

$collection | % { $_ }                    # SelectMany in PowerShell for array of arrays
$collection | % { $_.GetChildren() }      # SelectMany in PowerShell for complex object
Run Code Online (Sandbox Code Playgroud)

$a = (1,2,3),('X','F'),'u','y'
$a.Length                # output is 4
($a | % { $_ }).Length   # output is 7
Run Code Online (Sandbox Code Playgroud)

另一个例子

$dirs = dir -dir c:
$childFiles = $dirs | % { $_.GetFiles() }
$dirs.Length          # output is 6
$childFiles.Length    # output is 119
Run Code Online (Sandbox Code Playgroud)


Kei*_*ill 8

我还要提到PowerShell相当于SelectMany Select-Object -ExpandProperty <property name of a collection>.但是,对于此示例,这不能很好地工作,因为该属性IPAddress是一个字符串数组.将字符串产品数组展平为具有附加其他属性的单个字符串,例如:

Get-WmiObject Win32_NetworkAdapterConfiguration | Where {$_.IPAddress} | 
    Select Description -Expand IPAddress
Run Code Online (Sandbox Code Playgroud)

不幸的是,PowerShell System.String专门处理对象,因此除了字符串的值(在本例中为IPAddress)之外,它不希望显示任何内容.让它也显示其他属性(本例中的描述)是不实际的(可能吗?)AFAICT.