【问题标题】:Powershell 2.0: how to -match or -like a string in hash table keysPowershell 2.0:如何 -match 或 -like 哈希表键中的字符串
【发布时间】:2016-10-06 22:50:39
【问题描述】:

对于 Powershell 2.0:

我有一个哈希表,其中有几个字符串作为键。与@{}.containskey 不同,是否可以使用通配符(例如"*xampl*")找到键(例如"examplekey")?

我设法完成了我想要的制作键列表并使用 Where-Object 作为过滤器。但是有没有更简单的方法呢?我认为当我添加新键时这种方法特别糟糕,因为我每次都需要重新创建列表。

【问题讨论】:

    标签: string key match hashtable powershell-2.0


    【解决方案1】:

    使用返回键数组(或单个键)的.Keys 属性和-like-notlike 运算符:

    if ($hash.keys -notlike '*xampl*') {
        $hash.example = 1
    }
    

    将键存储在数组中以进行多次检查:

    $keys = $hash.keys
    if ($keys -notlike '*xampl*') {
        $hash.example = 1
    }
    if ($keys -notlike '*foo*') {
        $hash.example = 1
    }
    

    链接比较:

    if ($hash.keys -notlike '*xampl*' -notlike '*123*') {
        $hash.example = 1
    }
    

    如果有很多键并且您想要执行大量检查,请使用正则表达式:

    if ($hash.keys -join "`n" -match '(?mi)xampl|foo|bar|^herp\d+|\wDerp$|^and$|\bso\b|on') {
       echo 'Already present'
    } else {
       $hash.foo123 = 'bar'
       # ......
    }
    

    (?mi) 表示m大写-insensitive 模式:每个键都单独测试。

    【讨论】:

      猜你喜欢
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2016-03-31
      • 2015-08-24
      • 2021-12-30
      相关资源
      最近更新 更多