[英]Why does -like operator in Powershell works without wildcard?
據我所知,該運算符僅適用於通配符語法,但為什么在這種情況下它實際上有效?
PS C:\Users\Danie\Pictures> Get-ChildItem | Where-Object {$_.Extension -Like ".jpg"}
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 4/3/2020 1:55 1253954 16009807808_f3f4709393_k.jpg
之所以可行,是因為您的Extension
屬性值恰好是.jpg
。
正如Lee_Dailey 所提到的,在模式中使用-like
而沒有任何通配符在功能上等同於$string -eq $pattern
。
-like
呢?! 在您的情況下,沒有功能差異,因為Extension
已經是[string]
類型 - 但是在進行字符串比較時使用-like
而不是-eq
有一個很好的理由 - 那就是-like
只進行字符串比較,這意味着您可以保證在比較期間兩個操作數都被視為字符串。
使用-eq
,進行的比較完全取決於左側(或lhs )操作數的類型:
PS C:\> $null -eq "" # $null is not a string
False
PS C:\> $null -like "" # But -like attempts to convert $null to [string], we get an empty one
True
這適用於任何操作數類型,而不僅僅是$null
:
PS C:\> (Get-Item C:\Windows) -eq 'C:\Windows' # [System.IO.DirectoryInfo] is also not [string]
False
PS C:\> (Get-Item C:\Windows) -like 'C:\Windows' # But `-like` treats it as one
True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.