PowerShell 中 –Match、-Like 和 –Contains 運算子的區別是什麼?
上述三個運算子(Match、Like 和 Contains)都是 PowerShell 中的比較運算子。**Match** 和 **Like** 運算子幾乎相似,唯一的區別在於萬用字元,而 **Contains** 運算子則完全不同。我們將透過示例瞭解它們的工作方式。
示例
PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "PowerShell" True PS C:\WINDOWS\system32> "This is a PowerShell String" -Like "PowerShell" False PS C:\WINDOWS\system32> "This is a PowerShell String" -Contains "PowerShell" False
如果您檢視上述示例的輸出,則只有 Match 語句的結果為 True,原因是當您在字串中匹配關鍵字時,它會檢查關鍵字是否存在。您使用的關鍵字是單個關鍵字還是連線詞並不重要。下面的語句也為真。
PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "Shell" True
但萬用字元 (*) 對 Match 運算子沒有幫助。
PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "*PowerShell*" parsing "*PowerShell*" - Quantifier {x,y} following nothing. At line:1 char:1 + "This is a PowerShell String" -Match "*PowerShell*" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], ArgumentException + FullyQualifiedErrorId : System.ArgumentException
因此,**Match** 條件不評估正則表示式運算子。相反,Like 運算子與萬用字元 (*) 一起使用。
PS C:\WINDOWS\system32> "This is a PowerShell String" -like "*PowerShell*" True
因此,萬用字元在 Match 和 Like 運算子之間起著重要作用。我們可以檢查 **Contains** 運算子是否使用了萬用字元 (*)。
PS C:\WINDOWS\system32> "This is a PowerShell String" -contains "*PowerShell*" False
**Contains** 運算子也不適用於萬用字元 (*) 字元。它與 **Match** 和 **Like** 完全不同,並且適用於**物件集合(陣列)**。
PS C:\WINDOWS\system32> "Apple","Dog","Carrot","Cat" -contains "dog" True
廣告