When the number of files/folders in an organization increases, the administrators might need to delete outdated files. With more and more machines getting remote, admins find this task increasingly difficult. Hexnode lets admins handle this action via scripts on Windows devices.
Disclaimer:
The Sample Scripts provided below are adapted from third-party Open-Source sites.
To delete a file
Batch Script
|
del “filename_with_location.ext” |
E.g., To delete the file test.txt in the Desktop of the user Deborah,
del “C:\Users\Deborah\Desktop\test.txt”
Powershell Script
|
remove-item “filename.ext” |
E.g., To delete the file test.txt in the Desktop of the user Deborah,
remove-item “C:\Users\Deborah\Desktop\test.txt”
Notes:
-
- The admin can also delete files older than a specific number of days.
The .bat script to delete .docx files that are older than 20 days from the location C:\Users\username\Documents\My Blogs is as follows:
|
@echo off forfiles /p “C:\Users\username\Documents\My Blogs” /s /m *.docx /d -20 /c “cmd /c del @path” echo Document files older than 20 days deleted pause exit |
- The.ps1 script to delete files older than 20 days is as follows:
|
Write-Host "Welcome to the archive example" #Give the location of folder from which files should be deleted $path= "C:\Scripting\" $DaysTOBeArchived = "-20" ## Files which were modified before three days will be deleted. $CurrentDate = Get-Date $DatetoBeDeleted = $CurrentDate.AddDays(-$DaysTOBeArchived) $files=Get-ChildItem $path -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoBeDeleted } Foreach ($file in $files){ Remove-Item $file.FullName |out-null Write-Host "Cleared the file "$file } |
To delete a folder
Batch Script
|
rmdir /Q/S “foldername_with_path” |
E.g., To delete a folder test in the Desktop of the user Deborah,
rmdir /Q/S “C:\Users\Deborah\Desktop\test”
Notes:
/S deletes all the files from the folder. /Q makes sure that the user is not asked for confirmation for deleting the folder.
Powershell Script
|
remove-item “foldername_with_path” -recurse |
E.g., To delete a folder test in the Desktop of the user Deborah,
remove-item “C:\Users\Deborah\Desktop\test” -recurse
Notes:
-
-
- The –recurse attribute ensures that all the files inside the folder are deleted.
- It is recommended to manually validate the script execution on a system before executing the action in bulk.
- Hexnode will not be responsible for any damage/loss to the system on the behavior of the script.