如何在 PowerShell 中检查数组是否包含不区分大小写的字符串
在 PowerShell 中使用数组时的一项常见任务是检查数组是否包含特定字符串。在 PowerShell 中,字符串比较可以区分大小写或不区分大小写。在本 PowerShell 教程中,我将解释如何在 PowerShell 中检查数组是否包含不区分大小写的字符串。
要在 PowerShell 中检查数组是否包含字符串而不考虑大小写,请使用 -inotcontains 运算符,该运算符执行不区分大小写的比较。例如,如果在数组 $array 中找到字符串“string”,则 $containsString=$array -inotcontains ‘string’ 将返回 $true,无论大小写。或者,您可以使用 -ccontains 进行区分大小写的检查。
在 PowerShell 中检查数组是否包含不区分大小写的字符串
区分大小写的检查在比较字符串时会考虑字母大小写(大写或小写)。相反,不区分大小写的检查会忽略大小写,并将“PowerShell”视为与“powershell”或“POWERSHELL”相同。
PowerShell 提供了不同的运算符和方法来执行字符串比较。有些本质上不区分大小写,而另一些默认情况下区分大小写,但可以修改以执行不区分大小写的比较。
使用 -contains 运算符
PowerShell 有一个名为 -contains 的内置运算符,用于检查集合(例如数组)是否包含特定元素。默认情况下,-contains 运算符不区分大小写。
这是一个简单的例子:
$array = 'Apple', 'Banana', 'Cherry'
$stringToCheck = 'apple'
if ($array -contains $stringToCheck) {
Write-Host "The array contains the string."
} else {
Write-Host "The array does not contain the string."
}在此示例中,即使数组中的“Apple”具有大写“A”且 $stringToCheck 变量均为小写,-contains 运算符仍将确认“apple” ' 在数组中。
您可以查看下面的屏幕截图:
使用 .Contains() 方法
检查数组中是否存在字符串的另一种方法是使用 PowerShell 中的 .Contains() 方法。但是,与 -contains 运算符不同,.Contains() 方法区分大小写。为了使其不区分大小写,必须先使用 .ToLower() 或 .ToUpper() 方法将数组元素和要检查的字符串转换为相同的大小写比较。
以下是如何以不区分大小写的方式使用 .Contains() 方法:
$array = 'Apple', 'Banana', 'Cherry'
$stringToCheck = 'apple'
# Convert both to the same case
$lowerCaseArray = $array.ToLower()
$lowerCaseStringToCheck = $stringToCheck.ToLower()
if ($lowerCaseArray.Contains($lowerCaseStringToCheck)) {
Write-Host "The array contains the string."
} else {
Write-Host "The array does not contain the string."
}使用 vs.code 或 Windows PowerShell ISE 运行 PowerShell 脚本后,您可以在下面的屏幕截图中看到输出:
使用Where-Object Cmdlet
PowerShell 中的 Where-Object cmdlet 允许您根据对象的属性或脚本块来过滤对象。您可以使用此 cmdlet 执行不区分大小写的搜索,方法是使用脚本块将数组元素与所需字符串进行比较,并将两者转换为相同的大小写。
这是使用 Where-Object 的示例:
$array = 'Apple', 'Banana', 'Cherry'
$stringToCheck = 'apple'
$result = $array | Where-Object { $_.ToLower() -eq $stringToCheck.ToLower() }
if ($result) {
Write-Host "The array contains the string."
} else {
Write-Host "The array does not contain the string."
}使用 -match 运算符
-match 运算符使用 regex(正则表达式)来比较字符串,并且在 PowerShell 中默认不区分大小写。当您需要检查模式而不是精确的字符串时,此运算符会很有用。
这是使用 -match 的示例:
$array = 'Apple', 'Banana', 'Cherry'
$stringToCheck = 'apple'
$result = $array -match $stringToCheck
if ($result) {
Write-Host "The array contains the string."
} else {
Write-Host "The array does not contain the string."
}结论
检查数组是否包含特定字符串是 PowerShell 脚本编写中的一项常见任务。 PowerShell 提供了多种方法来执行此检查,不区分大小写是某些运算符和方法的默认行为,例如 -contains 和 -match。对于默认区分大小写的方法,例如 .Contains(),您可以通过在检查之前将字符串转换为相同的大小写来轻松执行不区分大小写的比较。
在本 PowerShell 教程中,我将解释如何使用以下方法在 PowerShell 中检查数组是否包含不区分大小写的字符串:
- 使用 -contains 运算符
- 使用 .Contains() 方法
- 使用Where-Object Cmdlet
- 使用 -match 运算符

