Powershell - 排除Get-ChildItem中的文件夹

问题描述 投票:3回答:3

如何排除文件夹?现在我硬编码文件夹名称,但我希望它更灵活。

foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb)
powershell
3个回答
6
投票

“如何排除文件夹?” ,如果你的意思是所有文件夹:

get-childitem "$fileDirectory\\*" -file 

但它仅适用于$ file目录的第一级。这递归地工作:

Get-ChildItem "$fileDirectory\\*"  -Recurse | ForEach-Object { if (!($_.PSIsContainer)) { $_}}

要么

 Get-ChildItem "$fileDirectory\\*"  -Recurse | where { !$_.PSisContainer }

5
投票

您可以使用管道和Where-Object过滤器来完成此操作。

首先,在PowerShell中迭代一组文件的惯用方法是将Get-Childitem管道传输到Foreach-Object。所以重写你的命令得到:

Get-ChildItem $fileDirectory | foreach {
   $file = $_
   ...
}

使用管道的优点是,现在您可以在其间插入其他cmdlet。具体来说,我们使用Where-Object来过滤文件列表。仅当文件未包含在给定数组中时,过滤器才会传递文件。

$excludelist = 'folderA', 'folderB'
Get-Childitem $fileDirectory | 
  where { $excludeList -notcontains $_ } |
  foreach {
    $file = $_
    ...
  }

如果你要经常使用它,你甚至可以编写一个自定义过滤器函数来以任意方式修改文件列表,然后再传递给foreach

filter except($except, $unless = @()) {
  if ($except -notcontains $_ -or $unless -contains $_ ){
    $_ 
  }
}

$excludelist = 'folderA', 'folderB'
$alwaysInclude = 'folderC', 'folderD'
Get-ChildItem $fileDirectory |
  except $excludeList -unless $alwaysInclude | 
  foreach {
    ...
  }

0
投票

@dvjz说--file只能在文件夹的第一级工作,但不能递归。但它似乎对我有用。

get-childitem "$fileDirectory\\*" -file -recurse
© www.soinside.com 2019 - 2024. All rights reserved.