1
votes

I have this script which tries to delete all the folders that are older than 7 days. All folders are located under a specific directory called "BackupPath"

This is the script:

 $date=Get-Date -UFormat "%d-%m-%y"
 $BackupPathday="C:\"+$env:computername+"GPOBackup\$date"
 $BackupPath="C:\"+$env:computername+"GPOBackup"

 if ((Test-Path $BackupPathday) -eq 0) {
 New-Item -ItemType Directory -Force -Path $BackupPathday
 }
 else {
 Write-Host "Today´s backup already exists"
 }

 $Folders=Get-ChildItem $BackupPath

 foreach ($i in $Folders) {
  $Days=((Get-Date) - $i.CreationTime).Days
  #PSISContainer is true means that $i is a folder, ohterwise is a file
  if ($Days -ge 7 -and $i.PsISContainer -eq $True) {       
   $i.Delete() 
  }
 }

When I run it, I get this error message:

Exception calling "Delete" with "0" argument(s): "The directory is not empty. " At C:\Users\x\Desktop\power.ps1:18 char:14 + $i.Delete <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException Exception calling "Delete" with "0" argument(s): "The directory is not empty. " At C:\Users\x\Desktop\power.ps1:18 char:14 + $i.Delete <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

Is there any way of force deleting these folders and its content? I don´t know if there is an existing method to do this as I´m new with PowerShell.

Thanks

1
I thought of that before too and It doesn´t work: Remove-Item : Cannot find path 'C:\Users\x\Desktop\26-09-15' because it does not exist...miticoluis
Unfortunately it doesn´t work either. Remove-Item : Cannot bind argument to parameter 'Path' because it is null.miticoluis
You might have to use GCI $path -Recurse | Remove-Itemuser4317867

1 Answers

1
votes

The -Directory switch gets just the folders then Where-object filters those folders based on the date criteria and finally remove-item removes them.(Remove Whatif to apply the command)

Get-ChildItem -Path $BackupPath -Directory | 
   Where-Object { ((get-date) - $_.CreationTime).days -ge 7} | 
         Remove-Item -Recurse -WhatIf

Also When testing for a non-existing directory use

if( -not (Test-path c:\temp) ) {"Do something"}else { "nothing"}

means if the expression evaluates to false then "Do something" else "nothing"