本文介绍了可以在 PowerShell 中简化以下嵌套的 foreach 循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个循环遍历数组并排除在第二个数组中找到的任何变量的脚本.

I have created a script that loops through an array and excludes any variables that are found within a second array.

虽然代码有效;这让我想知道它是否可以简化或管道化.

While the code works; it got me wondering if it could be simplified or piped.

   $result = @()
   $ItemArray = @("a","b","c","d")
   $exclusionArray = @("b","c")

    foreach ($Item in $ItemArray)
    {
        $matchFailover = $false
        :gohere
        foreach ($ExclusionItem in $exclusionArray)
        {
            if ($Item -eq $ExclusionItem)
            {
                Write-Host "Match: $Item = $ExclusionItem"
                $matchFailover = $true
                break :gohere
            }
            else{
            Write-Host "No Match: $Item != $ExclusionItem"
            }
        }
        if (!($matchFailover))
        {
            Write-Host "Adding $Item to results"
            $result += $Item
        }
    }
    Write-Host "`nResults are"
    $result

推荐答案

您可以将 Where-Object-notcontains 一起使用:

You can use Where-Object with -notcontains:

$ItemArray | Where-Object { $exclusionArray -notcontains $_ }

输出:

a, d

这篇关于可以在 PowerShell 中简化以下嵌套的 foreach 循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:29