【问题标题】:Filtering files with -notcontains使用 -notcontains 过滤文件
【发布时间】:2016-05-03 17:37:34
【问题描述】:

我正在尝试过滤等于 .config 的文件扩展名,并且文件名中不包含 vshost,因此我运行此脚本:

$files = dir
foreach($file in $files) {
    if($file.Name -notcontains 'vshost' -and $file.Extension -eq '.config') {
        Write-Host $file;
    }
}

但输出仍然包含名称中带有vshost 的文件:

foo.exe.config
foo.vshost.exe.config
foo2.vshost.exe.config

预期的输出是:

foo.exe.config

我缺少什么以及如何解决这个问题?

【问题讨论】:

  • -notcontains 是集合运算符,而不是字符串运算符。 -notlike '*vshost*'
  • 对不起,因为令人困惑而投反对票,这是我第一次使用 power shell 脚本。
  • 这可能是因为您应该通过阅读帮助(显示很少的研究工作)来弄清楚这一点:-) technet.microsoft.com/en-us/library/hh847759.aspx

标签: .net windows powershell


【解决方案1】:

-notcontains 用于在数组中查找项目,例如。 $array -notcontains $singleitem。您需要使用-notlike-notmatch(正则表达式模式)。例如。

if($file.Name -notlike '*vshost*' -and $file.Extension -eq '.config') {

if($file.Name -notmatch 'vshost' -and $file.Extension -eq '.config') {

【讨论】:

    【解决方案2】:

    -contains/-notcontains 用于检查列表是否包含元素。您可以使用-like / -notlike-match 运算符。

    在您的示例中,您可以使用

    $files = dir
    foreach($file in $files) {
        if($file.Name -notlike '*vshost*' -and $file.Extension -eq '.config') {
            Write-Host $file;
        }
    }
    

    可以参考here

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2014-09-15
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多