【问题标题】:Powershell: Exclude numerous folders with -notmatch statementPowershell:使用 -notmatch 语句排除大量文件夹
【发布时间】:2014-10-14 15:07:30
【问题描述】:

我正在创建一个小脚本,它将列出计算机上的 EXE 文件。

$computername = get-content env:computername
get-childitem C: -recurse | ? {$_.fullname -notmatch 'C:\\Windows'} | where {$_.extension -eq ".exe"} | format-table fullname | Out-File "\\server\incomming\$computername.txt"

问题在于 -notmatch 不接受更多语句。我可以复制粘贴? {$_.fullname -notmatch 'C:\\Windows'} 并用于其他文件夹,如 Program Files (x86)、Program Files 等。但我不想让脚本过于臃肿。

有没有办法可以用 -notmatch 语句排除大量文件夹?

【问题讨论】:

    标签: powershell get-childitem


    【解决方案1】:

    您可以使用-and 等逻辑运算符来处理更复杂的逻辑表达式。

    Get-ChildItem C:\ -Recurse | Where-Object { ($_.FullName -notmatch "C:\\Windows") -and ($_.FullName -notmatch "C:\\Program Files") }   
    

    对于许多路径,我会在调用Get-ChildItem 之前将它们添加到数组或哈希表中,并使用Where-Object 检查数组或哈希表中是否存在管道文件对象路径。最终,您必须在某处列出路径,但不一定在单个命令中。例如:

    $excludedPaths = @("C:\Windows", "C:\Program Files");
    Get-ChildItem C:\ -Recurse | Where-Object { $excludedPaths -notcontains $_.Directory }
    

    【讨论】:

      【解决方案2】:

      感谢您的回答!

      是否有可能获得比现在更长的输出时间?

      它现在大约有 100 个符号,如果路径长于此,则以点结尾。 我得到了这样的东西- C:\我的文件\我的程序\程序...

      【讨论】:

      • PowerShell 这样做是为了使输出在表格格式中可读。您始终可以将结果保存到文件中(例如| Export-Csv),或者使用| Format-List 将换行而不是添加省略号。 | Select-Object -Property FullName | Format-List 将只返回文件名。
      【解决方案3】:

      我会使用这样的东西:

      get-childitem -literalpath e:\*.exe -Recurse | where { $_.DirectoryName -notmatch "Windows" -and $_.DirectoryName -notmatch "MyOtherFiles"}
      

      【讨论】:

      • $_.DirectoryName 不好,你仍然会得到匹配的文件,例如。 \Windows\System32
      • DirectoryName 只是字符串格式的项目文件夹,如果要精确,您想将 -notmatch 替换为 -ne 并拼出文件夹名称,即 $_.DirectoryName -ne "e :\windows"
      猜你喜欢
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 2013-08-13
      • 1970-01-01
      • 2018-12-13
      相关资源
      最近更新 更多