如何在 PowerShell 中检查数组是否不包含字符串
在本 PowerShell 教程中,我将解释如何在 PowerShell 中检查数组是否不包含字符串。
要验证 PowerShell 中的数组不包含特定字符串,可以使用 -notcontains 运算符进行区分大小写的检查。例如,如果“specicString”不在数组 $array 中,$notPresent=$array -notcontains ‘specificString’ 将返回 $true。对于不区分大小写的检查,请将 -notcontains 替换为 -inotcontains。
在 PowerShell 中检查数组是否不包含字符串
现在,让我们讨论如何在 PowerShell 中检查数组是否不包含字符串的各种方法。
使用 -notcontains 运算符
PowerShell 提供了一个简单的运算符来检查数组是否不包含特定元素:-notcontains 运算符。如果数组不包含指定值,则此运算符返回 True,否则返回 False。
这是一个简单的例子:
# Define an array of strings
$array = @('apple', 'banana', 'cherry')
# Check if the array does not contain the string 'banana'
$result = $array -notcontains 'banana'
# Output the result
$result # This will output False because 'banana' is in the array
在此示例中,我们定义了一个包含三个水果名称的数组 $array。然后,我们使用 -notcontains 运算符来检查“banana”是否不在数组中。由于“banana”确实在数组中,因此 $result 将为 False。
现在,让我们检查一个不在数组中的字符串:
# Check if the array does not contain the string 'date'
$result = $array -notcontains 'date'
# Output the result
$result # This will output True because 'date' is not in the array在本例中,“date”不是 $array 的元素,因此 $result 将为 True。
我使用 VS code 执行了 PowerShell 脚本,您可以在下面的屏幕截图中看到输出:
将自定义过滤与Where-Object结合使用
确定数组是否不包含字符串的另一种方法是使用 PowerShell 中的 Where-Object cmdlet。此 cmdlet 允许您根据自定义条件过滤数组。
以下是如何使用 Where-Object 来实现我们的目的:
# Define an array of strings
$array = @('apple', 'banana', 'cherry')
# Use Where-Object to filter the array
$result = $array | Where-Object { $_ -ne 'banana' }
# Check if the result contains any elements
if ($result.Count -gt 0) {
$containsOtherThanBanana = $true
} else {
$containsOtherThanBanana = $false
}
# Output the result
$containsOtherThanBanana # This will output True在此代码段中,我们将 $array 通过管道传输到 Where-Object,指定过滤掉的脚本块 { $_ -ne 'banana' } '香蕉'。 $_ 变量表示管道中的当前项目。如果 $result 的元素超过零,则意味着该数组包含“banana”以外的元素。
使用循环进行自定义逻辑
有时,如果 PowerShell 数组不包含特定字符串,您可能希望执行更复杂的检查或操作。在这种情况下,循环会很有帮助。
考虑以下使用 foreach 循环的示例:
# Define an array of strings
$array = @('apple', 'banana', 'cherry')
# Variable to hold the check result
$notContainsString = $true
# Loop through each item in the array
foreach ($item in $array) {
if ($item -eq 'banana') {
# If 'banana' is found, set the flag to False
$notContainsString = $false
break # Exit the loop
}
}
# Output the result
$notContainsString # This will output False
在此脚本中,我们循环遍历 $array 的每个元素并检查它是否等于“banana”。如果找到“banana”,我们将 $notContainsString 设置为 False 并使用 break 提前退出循环。
结论
检查数组是否不包含特定字符串是 PowerShell 脚本编写中的一项常见任务。 -notcontains 运算符是执行此检查的最直接方法。对于更复杂的场景或者当您需要根据检查执行其他操作时,您可以使用 Where-Object 或循环以及条件逻辑。
在此 PowerShell 脚本中,我解释了如何检查 PowerShell 中的数组是否不包含特定字符串。
