为什么要使用
据我所知,这个运算符只适用于通配符语法,但为什么在这种情况下它真的有效呢?
PS C:UsersDaniePictures> 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_Dayey所提到的,在模式中使用不带任何通配符的-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