Powershell清理脚本。排除的文件夹未被排除

时间:2016-11-25 09:44:02

标签: powershell

我写了一个简单的脚本,每个周末都会作为计划任务运行。此脚本清除超过#day的文件,您可以将要排除的文件夹的名称作为参数。脚本不应清除此文件夹。但不知何故,该脚本仍然从排除文件夹中删除一些文件。但是以一种奇怪的方式没有文件匹配参数的条件。

例如,我运行脚本删除超过15天的文件并排除文件夹NOCLEANUP。但是某些文件仍然会从该文件夹中删除,但NOCLEANUP文件夹中仍有超过15天的文件。

以下代码

提前感谢并为脏代码道歉。 PS还是新手。

Function CleanDir ($dir, $days, $exclude, $logpath)
{
$Limit = (Get-Date).AddDays(-$days)
$Path = $dir
#Folder to exclude
$ToExclude = $exclude
#Log location
$Log= $logpath 
$Testpath = Test-Path -PathType Container -Path $Log

if ($Testpath -ne $true)
{

New-Item -ItemType Directory -Force -Path $Log

} 

#Logs deleted files

cd $Log
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $Limit } | Where-Object { $_.fullname -notmatch $ToExclude} | Where-Object { $_.fullname -notmatch '$RECYCLE.BIN'} | Out-File -FilePath CLEANUPLOG.TXT

# Delete files older than the $Limit.
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $Limit } | Where-Object { $_.fullname -notlike $ToExclude} | Remove-Item -Force -Recurse

#Goes into every folder separately and deletes all empty subdirectorys without deleting the root folders.

$Folder = Get-ChildItem -Path $Path -Directory

$Folder.fullname | ForEach-Object  
{ 
                           Get-ChildItem -Path $_ -Recurse -Force | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetFiles().Count -eq 0} | Remove-Item -Force -Recurse

} 
}

0 个答案:

没有答案
相关问题