Powershell:单个脚本来“清理”多个文件夹的旧文件

MaC*_*ban 3 scripting windows powershell filesystems powershell-v3.0

我想创建一个维护脚本,该脚本将在我们的每台服务器上运行以清除常见的 drop/archive 目录。脚本最好将参考文件用于文件夹路径和所需的时效限制。然后脚本将清除超过老化限制的文件路径。输入参考文件如下所示:

c:\logs\iis\siteA\ 30
c:\logs\job1\ 60
e:\archive\clientA\ 90
Run Code Online (Sandbox Code Playgroud)

第一个组件是文件路径;第二个是文件应该保留的天数,用空格隔开。

现在对于脚本,我有以下内容;然而,我尴尬地缺乏脚本经验。(我更注重网络)

#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}
Run Code Online (Sandbox Code Playgroud)

我觉得逻辑很接近,但我的语法关闭了。我的方法可行吗?有没有更好的办法?你能帮忙解释一下语法吗?使用 poweshell v3。

我从这篇文章中从deadlydog那里得到了很多逻辑。

Kat*_*ard 7

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

c:\logs\iis\siteA\ -30
c:\logs\job1\ -60
e:\archive\clientA\ -90
Run Code Online (Sandbox Code Playgroud)

我单独测试了新的代码部分,但我认为它仍然可以做你想做的事。

$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"
}
Run Code Online (Sandbox Code Playgroud)

它将它移动到不同目录的原因是因为递归删除中显然存在一个错误,而且我的数据有很多很多子目录,所以一旦我将所有内容移动到 kill 目录,我就运行这个:

del /f/s/q f:\delete > nul
rmdir /s/q f:\delete
Run Code Online (Sandbox Code Playgroud)

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

$del_dir = "f:\delete"
$fso = New-Object -ComObject scripting.filesystemobject
$fso.DeleteFolder($del_dir)
Run Code Online (Sandbox Code Playgroud)