Powershell:单个脚本来“清理”比

我想创build一个维护脚本,在我们的每台服务器上运行,以清除常见的drop / archive目录。 优选地,脚本将使用文件夹path的参考文件和期望的老化限制。 然后,脚本会清理比老化限制更早的文件path。 input引用文件看起来像这样:

c:\logs\iis\siteA\ 30 c:\logs\job1\ 60 e:\archive\clientA\ 90 

第一个组件是文件path; 第二个是文件应保留的天数,用空格分隔。

现在为脚本我有以下; 然而,我的脚本经验令人尴尬。 (我更关注networking)

 #Attempted loop Foreach ($ParentDir = Get-Content .\paths.txt $arg1, $arg2) {$limit = (Get-Date).AddDays(-$arg2) $path = $ParentDir # Delete files older than the $limit. Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force} 

我觉得这个逻辑很接近,但是我的语法是closures的。 我的方法可行吗? 有没有更好的办法? 你能帮忙吗? 使用poweshell v3。

信用信用是由于我从这个职位致死的狗采取了很多的逻辑。

编辑包含您请求的文本文件

 c:\logs\iis\siteA\ -30 c:\logs\job1\ -60 e:\archive\clientA\ -90 

我testing了一些新的代码,与我所处的位置不同,但是我认为它仍然应该做你想做的。

 $controlfile = "c:\path\to\yourfile.txt" $curr_date = Get-Date New-Item -ItemType directory -Path f:\delete foreach ($line in get-content $controlfile) { $split = $line.split(" ") $file_path = $split[0] $max_days = $split[1] $del_date = $curr_date.AddDays($max_days) # move the files to the kill directory Get-ChildItem $file_path | Where-Object { $_.LastWriteTime -lt $del_date } | Move-Item -destination "f:\delete" } 

把它移动到不同目录的原因是因为在recursion删除中显然有一个bug ,而且我的数据有很多很多的子目录,所以一旦我把所有的东西都移到了kill目录下,我就运行这个:

 del /f/s/qf:\delete > nul rmdir /s/qf:\delete 

如果你没有这个问题,你可以把它添加到上面的PowerShell的末尾:

 $del_dir = "f:\delete" $fso = New-Object -ComObject scripting.filesystemobject $fso.DeleteFolder($del_dir) 

您可以为此创build一个cmdlet,因此您也可以在命令行中使用它:

小命令

 param( [string]$folder, [int]$expiry ) ls $folder | % { if ($_.LastWriteTime -le (date).AddDays(-$expiry)) { rm $_ -fo } } 

用法

 .\script.ps1 -folder "c:\logs\iis\siteA\" -expiry 30 .\script.ps1 -folder "c:\logs\job1\" -expiry 60 .\script.ps1 -folder "e:\archive\clientA\" -expiry 90