To delete objects, use the Remove-Item cmdlet. If the object is not empty, you’ll be prompted to confirm the deletion. Here’s how to delete the “IT” folder and all the subfolders and files inside it:
Remove-Item -Path '\\fs\shared\it\'
Confirm
The item at \\pdc\shared\it has children and the Recurse parameter was not specified. If you
continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):
If you have already made sure that every object inside the folder should be deleted, you can use the -Recurse switch to skip the confirmation step:
Remove-Item -Path '\\fs\shared\it\' -Recurse
Deleting Old Files
Sometimes you need to clean up old files from a certain directory. Here’s the way to accomplish that:
$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
}
Check if File Exists Before Deleting
Here’s how to check whether a file exists and delete it if it does:
$FileName = 'C:\data\log.txt'
If (Test-Path $FileName) {
Remove-Item $FileName
}
Deleting Files from Remote PCs
To delete files from remote PCs, you must have the appropriate security permissions to access them. Be sure to use UNC paths so the script will correctly resolve the file locations.
$filelist = @("\c$\Temp", "\c$\Backups") # Variable to delete files and folder
$computerlist = Get-Content C:\data\pc.txt # Get list of remote pc's
foreach ($computer in $computerlist) {
foreach ($file in $filelist) {
$filepath = Join-Path "\\$computer\" "$filelist" # Generate unc paths to files or folders
if (Test-Path $filepath) {
Remove-Item $filepath -force -recurse -ErrorAction Continue
}
}
}