[英]Why does -like operator in Powershell works without wildcard?
As far as I know this operator works only with wildcard syntax but why in this case it actually worked out?据我所知,该运算符仅适用于通配符语法,但为什么在这种情况下它实际上有效?
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
It works out because the Extension
property value in your case is exactly .jpg
.之所以可行,是因为您的Extension
属性值恰好是.jpg
。
As Lee_Dailey mentions , using -like
without any wildcard characters in your pattern is functionally equivalent to $string -eq $pattern
.正如Lee_Dailey 所提到的,在模式中使用-like
而没有任何通配符在功能上等同于$string -eq $pattern
。
-like
then?!那为什么要使用-like
呢?! In your case there's no functional difference because Extension
is already of type [string]
- but there is one good reason to use -like
over -eq
when doing string comparisons - and that is that -like
only does string comparison , meaning that you can guarantee both operands are treated as strings during comparison.在您的情况下,没有功能差异,因为Extension
已经是[string]
类型 - 但是在进行字符串比较时使用-like
而不是-eq
有一个很好的理由 - 那就是-like
只进行字符串比较,这意味着您可以保证在比较期间两个操作数都被视为字符串。
With -eq
, the comparison being made depends entirely on the type of the left-hand side ( or lhs ) operand:使用-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
This goes for any operand type, not just $null
:这适用于任何操作数类型,而不仅仅是$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.