当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何在 PowerShell 中检查数组中是否不存在某个项目

作者:精品下载站 日期:2024-12-14 05:06:02 浏览:14 分类:玩电脑

如何在 PowerShell 中检查数组中是否不存在某个项目


您是否需要检查 PowerShell 数组中是否不存在某项?在本 PowerShell 教程中,我将通过示例解释如何使用各种方法检查 PowerShell 中的数组中是否不存在某项。

要检查 PowerShell 中的数组中是否不存在某项,请使用 -notcontains 运算符。例如,如果数组 $array 中不存在“item”,$doesNotExist=$array -notcontains “item”将返回 $true。该运算符执行区分大小写的搜索;对于不区分大小写的检查,请使用 -inotcontains 代替。

在 PowerShell 中检查数组中是否不存在某个项目

让我们看看如何在 PowerShell 中检查数组中是否不存在某个项目的各种方法。

使用 -contains 运算符

PowerShell 中的 -contains 运算符用于检查数组是否包含特定值。要检查数组中是否不存在某项,可以将 -contains 运算符与逻辑 not 运算符 ! 结合使用。

这是一个例子:

$array = 'apple', 'banana', 'cherry'
$item = 'mango'

if (-not ($array -contains $item)) {
    Write-Host "The item '$item' does not exist in the array."
}

在此示例中,脚本检查 $item(‘mango’)是否不在 $array 中。由于“mango”不是 $array 的元素,因此条件计算结果为 $true,并且显示消息。

您可以查看下面的屏幕截图,了解我使用 Visual Studio Code 执行 PowerShell 脚本后的输出。

[玩转系统] 如何在 PowerShell 中检查数组中是否不存在某个项目

使用 -notcontains 运算符

或者,PowerShell 提供 -notcontains 运算符,它是 -contains 的直接否定。如果数组不包含指定的项目,则返回$true

这是完整的示例:

$array = 'apple', 'banana', 'cherry'
$item = 'mango'

if ($array -notcontains $item) {
    Write-Host "The item '$item' does not exist in the array."
}

这与第一个示例相同,但使用 -notcontains 以获得更直接和可读的方法。

使用 .Contains() 方法

.Contains() 方法是来自 [System.Collections.ArrayList][System.Collections.Generic.List[T]] .NET 中的类型,PowerShell 可以使用它来检查数组(或更准确地说,列表)是否包含特定值。

要使用此方法,您应该首先将数组转换为 [System.Collections.ArrayList] 或创建一个 [System.Collections.Generic.List[T]] 对象。

这是一个完整的例子:

[array]$array = @('apple', 'banana', 'cherry')
$item = 'mango'

if (-not $array.Contains($item)) {
    Write-Host "The item '$item' does not exist in the array."
}

请记住,此方法区分大小写,并且数组必须转换为 [array] 或列表类型,.Contains() 方法才可用。

使用自定义函数

如果您发现自己重复检查数组中不存在的项目,您可能需要创建一个自定义函数来简化该过程。

这是一个完整的PowerShell自定义函数。

function Test-NotInArray {
    param(
        [Parameter(Mandatory=$true)]
        [array]$Array,
        [Parameter(Mandatory=$true)]
        $Item
    )
    return -not ($Array -contains $Item)
}

$array = 'apple', 'banana', 'cherry'
$item = 'mango'

if (Test-NotInArray -Array $array -Item $item) {
    Write-Host "The item '$item' does not exist in the array."
}

此自定义函数 Test-NotInArray 可以在整个脚本中重复使用,以采用干净且一致的方法来检查 PowerShell 数组中不存在的项目。

结论

可以使用各种方法检查数组中是否不存在某项。您是否选择将 PowerShell -contains 运算符与 not 一起使用、-notcontains 运算符、.Contains() > 方法,或自定义函数,您现在有多种方法可以有效地执行此检查。

在本 PowerShell 教程中,我解释了如何使用不同的方法检查 PowerShell 数组中是否不存在某个项目

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯