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
GCI $path -Recurse | Remove-Item
– user4317867