Data Networking Blog
Blog for Admins

Powershell script to delete old files/folders


Powershell script to delete old files/folders

The script below will delete any files/folders older than the provided number of days. It first creates an inverted tree of folder/file structure and then loops through each to see if the last write time is older than a given number of days. You can also clean empty folders by setting the variable delEmptyFolders to 1 otherwise this script will ignore the folders which may be suitable in some cases.



EDIT: Learned something new today. IF I add the folders like below then it works fine as long as there are more than one subfolders in the directory. But if there is only one then it appends the $directory to the previous folder and fails with errors.

$folders = Get-ChildItem $directory -rec | ? {$_.PSIsContainer -eq $true} | select-object -ExpandProperty FullName | sort-object -Descending
$folders += $directory


To fix do it like this so it always creates proper array

$folders = @(Get-ChildItem $directory -rec | ? {$_.PSIsContainer -eq $true} | select-object -ExpandProperty FullName | sort-object -Descending)
$folders += @($directory)

August 20, 2015 Script, Windows Jd

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Font Size
Decrease Size Default Size Increase Size
Select Skin
Select Underlay Background
Select Overlay Background
Scheme Switcher Toggle