代码之家  ›  专栏  ›  技术社区  ›  Rakha

其中对象优化PowerShell

  •  0
  • Rakha  · 技术社区  · 7 年前

    我有一个正确的命令:

    $FichierXML = get-childitem "$PsScriptRoot" | Where-Object { ($_.Name -notlike "creer*") -and ($_.Name -notlike "des*") -and ($_.Name -notlike "ins*")  -and ($_.Name -like "*.XML") }
    

    它找到一个.xml文件,文件名中不包含3个单词“creer”、“des”和“in s”。

    我的问题是,有没有一个最佳的方法来代替我正在做的对象的多个条件?也许是一条很短的路?当然可以,不过我一直很想学更好的方法。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Theo    7 年前

    可能是这样的:

    $FichierXML = Get-ChildItem "$PsScriptRoot" -Filter '*.XML' | Where-Object { $_.Name -notmatch '^(creer|des|ins)' }
    

    使用 -Filter 只获取的参数 .XML 文件和使用正则表达式 -notmatch 文件名。

        2
  •  1
  •   G42    7 年前

    -in -notin 但它们检查多个值是否完全匹配。什么都不像 -notlikein 或者类似的事情。

    不是100%,但相信这应该有效:

    $FichierXML = Get-ChildItem "$PSScriptRoot" |
                    Where-Object {$_.Name -notmatch "^(creer|des|ins)" -and $_.Name -like "*.XML"}
    

    说明:

    • -[not]match 使用正则表达式, -[not]like
    • | 充当逻辑“或”
    • ^ 指定字符串的开头
    • () 扩大了,所以你 ^creer ,请 ^des , ^ins

    相关: Operators documentation

    编辑 :合并更正 Matt's comment

    推荐文章