如何排除文件夹?现在我硬编码的文件夹名称,但我希望它更灵活。Powershell - 排除Get-ChildItem中的文件夹
foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb)
如何排除文件夹?现在我硬编码的文件夹名称,但我希望它更灵活。Powershell - 排除Get-ChildItem中的文件夹
foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb)
“如何排除文件夹?” ,如果你的意思是所有的文件夹:
get-childitem "$fileDirectory\\*" -file
但它只适用于$ fileDirectory的第一级。 这工作recursevly:
Get-ChildItem "$fileDirectory\\*" -Recurse | ForEach-Object { if (!($_.PSIsContainer)) { $_}}
或
Get-ChildItem "$fileDirectory\\*" -Recurse | where { !$_.PSisContainer }
您可以通过使用管道和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 {
...
}
如果我没有错,这仍然需要指定要排除的文件夹名称。示例如果我有100个文件夹,我需要指定它们中的每一个100次。现在我想跳过这个手动过程 – user664481
您需要建立一个文件夹列表来排除这种或那种方式,无论是手动执行还是运行不同的'Get-ChildItem'命令。这取决于您如何选择要排除的文件夹。 –
@dvjz说-file只能在一个文件夹中的第一级,但不递归。但它似乎为我工作。
get-childitem "$fileDirectory\\*" -file -recurse
您的意思是排除* all *文件夹吗?或者只是你选择的那些? –