我为实习编写了一个简单的脚本,该脚本会遍历提供的目录并删除任何早于指定天数的文件。我今天花了所有的空闲时间试图加强它。这是我到目前为止所得到的:
function delOld($dir, $numDays){
$timespan = new-timespan -days $numDays
$curTime = get-date
get-childItem $dir -Recurse -file |
where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
remove-Item -whatif
}
以下是该函数的调用示例:
delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5
抱歉阅读困难,我发现将操作压缩成一行比每次迭代将它们重新分配给清晰的变量更有效。出于测试目的,目前已删除项目。我知道此时我可能无法加快速度太多,但是,我正在超过 TB 的文件上运行它,因此每个操作都很重要。
预先感谢您提供的任何建议!
停留在 PowerShell 和 .NET 方法的领域,以下是加速函数的方法:
计算截止时间戳once,在前面。
-
Use the [IO.DirectoryInfo]
type's EnumerateFiles()
method (PSv3+ / .NET4+) in combination with a foreach
statement. Tip of the hat to wOxxOm https://stackoverflow.com/users/3959875/woxxom.
调用.Delete()
方法直接在每个[System.IO.FileInfo]
循环体内的实例。
Note: For brevity, there are no error checks in the function below, such as for whether $numDays
has a permissible value and whether $dir
refers to an existing directory (if it's a path based on a custom PS drive, you'd have to resolve it with Convert-Path
first).
function delOld($dir, $numDays) {
$dtCutoff = [datetime]::now - [timespan]::FromDays($numDays)
# Make sure that the .NET framework's current dir. is the same as PS's:
[System.IO.Directory]::SetCurrentDirectory($PWD.ProviderPath)
# Enumerate all files recursively.
# Replace $file.FullName with $file.Delete() to perform actual deletion.
foreach ($file in ([IO.DirectoryInfo] $dir).EnumerateFiles('*', 'AllDirectories')) {
if ($file.LastWriteTime -lt $dtCutOff) { $file.FullName }
}
}
注:以上只是简单的outputs要删除的文件的路径;代替$file.FullName
with $file.Delete()
执行实际删除。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)