【问题标题】:Why does -like operator in Powershell works without wildcard?为什么 Powershell 中的 -like 运算符在没有通配符的情况下工作?
【发布时间】:2020-04-17 11:13:06
【问题描述】:

据我所知,此运算符仅适用于通配符语法,但为什么在这种情况下它确实有效?

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

【问题讨论】:

  • 当您省略通配符时,-like 运算符充当-eq 运算符。
  • @Lee_Dailey 还有一个区别 - -like always 将两个操作数强制转换为 [string]
  • @MathiasR.Jessen - 哦!我没有想到...这是有道理的,寿。谢谢你的信息! [咧嘴]

标签: powershell syntax scripting


【解决方案1】:

因为在您的情况下,Extension 属性值是 完全 .jpg

作为Lee_Dailey mentions,在您的模式中使用不带任何通配符的-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

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    相关资源
    最近更新 更多