Powershell Uncategorized

PowerShell to delete folders/files older than x days

Delete files automatically.

If you only need to keep files/folders for a certain amount of time, you can use this script to delete anything older than x days.

GET-CHILDITEM -PATH "N:\disk-counters\" -RECURSE -DIRECTORY| WHERE-OBJECT {($_.lastwritetime -LT (GET-DATE).adddays(-24))} |REMOVE-ITEM -RECURSE -FORCE

Get-ChildItem -Directory will get all the directory (folders) from the -Path N:\disk-counters\

| Where-Object {($_.lastwritetime -LT (GET-DATE).adddays(-24)) will filter out Directory that are more than 24 days old

|Remove-Item will remove these folders

You can easily modify this script to delete files instead of folders, and you can use *.* to delete everything older than x days or put the file extension if you only need to delete files with certain file extensions.

To automate this, create a service account with logon as a service right and configure a scheduled task to run this in a schedule.

change the user or Group to add the service account to run the task.

start Powershell and then put in Add arguemtns

-ExecutionPolicy RemoteSigned -File "C:\script\delete_file.ps1"

Put either Remotesigned or Bypass as parameter for -ExecutionPolicy and put the path where you saved your PowerShell file.

Optionally, if you want to prevent the PowerShell window to popup, you can add the -Windowstyle hidden parameter to hide the window.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s