简体   繁体   中英

delete directory object and its content in powershell

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM