简体   繁体   中英

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 .

As Lee_Dailey mentions , using -like without any wildcard characters in your pattern is functionally equivalent to $string -eq $pattern .


Why use -like then?!

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.

With -eq , the comparison being made depends entirely on the type of the left-hand side ( or lhs ) operand:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM