param ( [int]$TestMode = 1, [int]$DeleteOlderThanMonths = 6, [string]$DeleteFileExtension = ".jpg", [string]$Root_Folder = "C:\", [string]$Logfile = "Log.txt" ) #writes log messages Function LogWrite { Param ([string]$logstring) $currentdate = get-date -format "M-d-yyyy HH:MM" Add-content $Logfile -value "$currentdate | $logstring" } #checks if zip file contains only DeleteFileExtension file type Function CanZIPbeDeleted($zipFilePath) { [int]$canBeDeleted = 1; try { $zipArchive = Get-Item -Path $zipFilePath | ForEach-Object { (New-Object -ComObject Shell.Application).NameSpace($_.FullName) } foreach($item in $zipArchive.items()) { if(!$item.Path.EndsWith($DeleteFileExtension)) { $canBeDeleted = 0 $msg = "$zipFilePath cannot be deleted as it contains non $DeleteFileExtension file" LogWrite $msg Write-Host $msg -foreground Green return 0 } } } catch { $msg = "Unexpected Error. Error details: $_.Exception.Message" LogWrite $msg Write-Host $msg -foreground Red return 0 } return $canBeDeleted; } #deletes the file Function DeleteFile($filePathToDelete) { try { if($TestMode -eq 0) { Remove-Item $filePathToDelete } $size = (Get-Item -Path $filePathToDelete | Select-Object Name, @{Name="Size";Expression={[string]::Format("{0:0.00} MB", $_.Length / 1MB)}}).Size $msg = "File deleted ($size): $filePathToDelete" LogWrite $msg Write-Host $msg -foreground "magenta" } catch { $msg = "Unexpected Error. Error details: $_.Exception.Message" LogWrite $msg Write-Host $msg -foreground Red } } get-childitem -Path $Root_Folder –recurse | where-object { $_.CreationTime -lt (get-date).addMonths(-$DeleteOlderThanMonths) -and ($_.FullName.EndsWith($DeleteFileExtension) -or $_.FullName.EndsWith(".zip")) } | Foreach-Object { if ($_.FullName.EndsWith(".zip")) { $canDeleteZip = CanZIPbeDeleted $_.FullName if($canDeleteZip -eq 1) { DeleteFile $_.FullName } } else { DeleteFile $_.FullName } }