3. File System Management Tasks - Powershell

3.3 Deleting Files and Folders

to delete a file, use the Remove-Item cmdlet. if the file is not empty, you will be prompted to confirm the deletion.

Remove-Item -Path test.txt

to remove all files and folders in a directory, use the Remove-Item cmdlet with the -Recurse parameter.

Remove-Item -Path C:\temp -Recurse

this will remove all files and folders in the C:\temp directory.


Clean up old files

$Folder = "C:\Backups"
#delete files older than 30 days
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
ForEach-Object {
$_ | del -Force
$_.FullName | Out-File C:\log\deletedbackups.txt -Append
}
#delete empty folders and subfolders if any exist
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {$_.PsIsContainer -eq $True} |
? {$_.getfiles().count -eq 0} |
ForEach-Object {
$_ | del -Force
$_.FullName | Out-File C:\log\deletedbackups.txt -Append
}

What This Script Does:

  1. Deletes Files Older Than 30 Days:
  • Searches the C:\Backups folder and its subfolders for files older than 30 days.
  • Deletes these files and logs their paths to C:\log\deletedbackups.txt.
  1. Deletes Empty Folders:
  • Finds empty folders in C:\Backups (including subfolders).
  • Deletes these folders and logs their paths to the same log file.