Powershell 中的 Foreach + If 函数无法正确从数组中删除项目

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

我是PS的初学者,所以请对我放轻松。我正在尝试编写一段代码,如果数组包含某种模式(在本例中为“Apple”和“Banana”),则从数组中删除整个元素。

我编写了下面的代码作为实际数据的占位符,以便我可以更好地了解正在发生的情况。第一次迭代删除了正确的项目,但之后它变得有点混乱。我哪里做错了?

$Text = @("Apple and Orange", "Pear and Grape", "Peach and Mango", "Avocado and Banana")
$x = 0

$NotItem = "Banana"
$NoSales = "Apple"

cls
foreach ($element in $Text)
    {
    # Remove elemets from array that don't contain purchasable items
    if ($element -contains $NotItem -or $element -match $NoSales)
        {
        $Text[$x] = $null
        $Next = $Text[$x]
        Write-Host "Condition Met. $element, Step $x, `n`n`    Current Array: $Text`n`n`    Next Item: $Next`n`n"
        }
    # If neither applies, move on
    else 
        {
        $x = $x + 1
        $Next = $Text[$x]
        Write-Host "Condition Not Met. $element, Step $x, `n`n`    Current Array: $Text`n`n`    Next Item: $Next`n`n"
        }
    }

输出如下:

Condition Met. Apple and Orange, Step 0, 

    Current Array:  Pear and Grape Peach and Mango Avocado and Banana

    Next Item: 


Condition Not Met. Pear and Grape, Step 1, 

    Current Array:  Pear and Grape Peach and Mango Avocado and Banana

    Next Item: Pear and Grape


Condition Not Met. Peach and Mango, Step 2, 

    Current Array:  Pear and Grape Peach and Mango Avocado and Banana

    Next Item: Peach and Mango


Condition Not Met. Avocado and Banana, Step 3, 

    Current Array:  Pear and Grape Peach and Mango Avocado and Banana

    Next Item: Avocado and Banana
powershell if-statement foreach
1个回答
0
投票

我假设您在运行代码后预计

'Avocado and Banana'
不会出现在
$Text
中,为此您还可以使用
-match
而不是
-contains
来在集合中查找完全匹配的内容。然而,通过改变你的
$Text
数组,你最终会得到
$null
值,这很可能是你不想要的,在这种情况下最好重新创建数组:

$Text = @('Apple and Orange', 'Pear and Grape', 'Peach and Mango', 'Avocado and Banana')
$x = 1

$NotItem = 'Banana'
$NoSales = 'Apple'
$newText = foreach ($element in $Text) {
    # Remove elemets from array that don't contain purchasable items
    $Next = $Text[$x++]
    if ($element -match $NotItem -or $element -match $NoSales) {
        Write-Host "Condition Met. $element, Step $x, Next Item: $Next"
    }
    # If neither applies, move on
    else {
        $element
        Write-Host "Condition Not Met. $element, Step $x, Next Item: $Next"
    }
}

$newText

使用

Where-Object
进行过滤的简化方法是:

$newText = $Text | Where-Object { $_ -notmatch $NotItem -or $_ -notmatch $NoSales }
© www.soinside.com 2019 - 2024. All rights reserved.