【问题标题】:Powershell equivalent to Python "in"?Powershell相当于Python“in”?
【发布时间】:2012-04-11 01:22:59
【问题描述】:

我最近一直在使用数组,真的很怀念 Python 的“in”运算符。

例如:

if ("hello" in ["hello", "there", "sup"]):
    print "this prints :)"

我通过创建一个“ThereExists-Object”函数来弥补这一点,如下所示:

function ThereExists-Object([System.Management.Automation.ScriptBlock] $sb)
{
    return ($input | where $sb) -as [bool]
}
New-Alias -Name ThereExists -Value ThereExists-Object

例如:

if ($arrayOfStuff | thereexists { $_ -eq "hello" } )
{
    write-host "this prints too"
}

显然我也可以为此定义另一个函数...但我想知道是否有一些我不熟悉的语法糖可以完成这项工作。

那么……有吗?

【问题讨论】:

    标签: python arrays powershell syntax


    【解决方案1】:
    $arrColors = "blue", "red", "green", "yellow", "white", "pink", "orange", "turquoise"
    $arrColors -contains "black" 
    False
    $arrColors -contains "blue"
    True
    

    来源:http://technet.microsoft.com/en-us/library/ee692798.aspx

    【讨论】:

    • 哈哈,谢谢...我一定没有在我的谷歌搜索中选择正确的关键字
    【解决方案2】:

    从 Powershell v3.0 开始,您可以使用 -in 运算符本身:

    PS> "hello" -in "hello", "there", "sup"
    True
    PS> "hell" -in "hello", "there", "sup"
    False
    

    【讨论】:

    • 嗯,这很酷......我想......除了它似乎是多余的。它们只是具有交换参数的相同运算符吗?
    • @Nacht - 我想说他们正在引入在其他语言中发现和常用的运算符
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2012-02-11
    • 2012-03-10
    相关资源
    最近更新 更多