如果我的回答看起来像之前的答案的重复,我只是想展示一种更新的解决方法(在POSH 5.0测试通过)。之前的答案都是针对3.0之前的版本,不像现代解决方案那样高效。
这份文档并没有明确说明,但Get-ChildItem -Recurse -Exclude
只匹配叶节点(Split-Path $_.FullName -Leaf
)上的排除项,而不是父路径(Split-Path $_.FullName -Parent
)上的。匹配排除项只会移除具有匹配叶节点的项;Get-ChildItem
仍将递归到该叶节点。
在POSH 1.0或2.0中
Get-ChildItem -Path $folder -Recurse |
? { $_.PsIsContainer -and $_.FullName -inotmatch 'archive' }
注意:与@CB的答案相同。
在POSH 3.0及以上版本中
Get-ChildItem -Path $folder -Directory -Recurse |
? { $_.FullName -inotmatch 'archive' }
注意:来自@CB的更新答案。
多个排除项
这特别针对目录,使用Exclude
参数排除叶子节点,使用ilike
(不区分大小写的类似)比较排除父节点:
[string[]]$Paths = @('C:\Temp', 'D:\Temp')
[string[]]$Excludes = @('*archive*', '*Archive*', '*ARCHIVE*', '*archival*')
$files = Get-ChildItem $Paths -Directory -Recurse -Exclude $Excludes | %{
$allowed = $true
foreach ($exclude in $Excludes) {
if ((Split-Path $_.FullName -Parent) -ilike $exclude) {
$allowed = $false
break
}
}
if ($allowed) {
$_
}
}
注意:如果您希望$Excludes
区分大小写,需要进行两个步骤:
- 从
Get-ChildItem
中删除Exclude
参数。
- 将第一个
if
条件更改为:
if ($_.FullName -clike $exclude) {
注意:此代码具有冗余性,在生产环境中我不会这样实现。您应该根据自己的需要对其进行简化。它作为详细示例使用得很好。