gpt4 book ai didi

powershell - 避免在 PowerShell 中递归获取特定文件夹

转载 作者:行者123 更新时间:2023-12-01 11:47:46 25 4
gpt4 key购买 nike

我有一个包含多个项目的 Visual Studio 解决方案。我使用以下脚本清理 bin 和 obj 文件夹作为清理的一部分。

Get-ChildItem -path source -filter obj -recurse | Remove-Item -recurse
Get-ChildItem -path source -filter bin -recurse | Remove-Item -recurse

这非常有效。但是,我有一个基于文件的数据文件夹,其中包含大约 600,000 个子文件夹,并且位于名为 FILE_DATA 的文件夹中。

上面的脚本需要很长时间,因为它遍历了所有这 600,000 个文件夹。

当我递归遍历和删除 bin 和 obj 文件夹时,我需要避开 FILE_DATA 文件夹。

最佳答案

这是一种更有效的方法,可以满足您的需要——跳过您想要排除的子树:

function GetFiles($path = $pwd, [string[]]$exclude)
{
foreach ($item in Get-ChildItem $path)
{
if ($exclude | Where {$item -like $_}) { continue }

$item
if (Test-Path $item.FullName -PathType Container)
{
GetFiles $item.FullName $exclude
}
}
}

此代码改编自 Keith Hill 对 this post 的回答;我的贡献是一个错误修复和小的重构;您会在我对同一个 SO 问题的回答中找到完整的解释。

这个调用应该做你需要的:

GetFiles -path source -exclude FILE_DATA

要更悠闲地阅读,请查看我在 Simple-Talk.com 上的文章,其中讨论了这一点以及更多内容:Practical PowerShell: Pruning File Trees and Extending Cmdlets .

关于powershell - 避免在 PowerShell 中递归获取特定文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com