Delete files without removing the folder tree in PowerShell

0

I have this script written in Powershell to delete files from a server using its creation date.

$datapath = "C:\Users\Alumno\Desktop\test"
dir $datapath| ?{($_.creationtime.adddays(2) -lt (get-date))} | remove-item -force -Recurse

How could I make the files ONLY? That is to say, that whenever you execute the script all the old files are deleted but that the folders, however old they are, remain intact.

    
asked by blee1d 05.02.2018 в 18:45
source

1 answer

0

Instead of using dir, you can start with the command Get-ChildItem to list all the objects and from there, separate those that comply with the age you define and with the particularity that they are not directories:

$datapath = "C:\Users\Alumno\Desktop\test"
Get-ChildItem $datapath -Recurse | ?{($_.creationtime.adddays(1) -lt (Get-Date))} | Where { ! $_.PSIsContainer } | Remove-Item

With the previous code the files will be deleted and the folder structure will be maintained. The filter for this is the block:

Where { ! $_.PSIsContainer }

Where we indicate that it is not a folder.

I hope I have solved the problem.

    
answered by 07.02.2018 / 16:10
source