如何排除文件夹?现在,我硬编码文件夹名,但我希望它更灵活。
foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb)发布于 2016-03-04 08:21:20
“如何排除文件夹?”,如果您指的是所有文件夹:
get-childitem "$fileDirectory\\*" -file 但它只适用于$fileDirectory的第一级。这种方法可以递归地工作:
Get-ChildItem "$fileDirectory\\*" -Recurse | ForEach-Object { if (!($_.PSIsContainer)) { $_}}或
Get-ChildItem "$fileDirectory\\*" -Recurse | where { !$_.PSisContainer }发布于 2016-03-04 07:18:50
您可以通过使用管道和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 {
...
}发布于 2017-12-25 00:37:00
@dvjz说,-file只在文件夹的第一级工作,而不是递归地工作。但它似乎对我有用。
get-childitem "$fileDirectory\\*" -file -recursehttps://stackoverflow.com/questions/35789888
复制相似问题