Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Use PowerShell to Delete Files and Folders?

Storage space is a crucial server resource to maintain. Dropping to critical free disk space causes many problems and could result in loss of service. Disk housekeeping is a typical maintenance task wherein you Delete files that may be past a certain age or is larger than a specific size.

In this post, we’ll learn how to use PowerShell to Delete Files and folders in different scenarios.

How to Delete Files with PowerShell?

First, the basics. The main star of this PowerShell delete item example is the Remove-Item cmdlet. This cmdlet accepts the filename using the -Path or -LiteralPath parameters. What’s the difference?

The Path parameter accepts expressions, while the LiteralPath parameter accepts only literal paths and does not interpret expressions.

In this example, let’s delete the file called C:\temp\logs\0ndx7grg.txt.

Remove-Item -Path C:\temp\logs\0ndx7grg.txt

As you can see, the command failed because the item may be a hidden, read-only, or system file.

And if we check the file’s attributes by running the command below.

Get-ItemProperty -Path C:\temp\logs\0ndx7grg.txt | Select-Object Attributes

True enough, the file is read-only.

How do we force delete a read-only file? By adding the -Force switch.

Remove-Item -Path C:\temp\logs\0ndx7grg.txt -Force

This time, the file was deleted without any errors. As you can see below, the file no longer exists.

PowerShell Delete Multiple Files

How about when there are multiple files? In this case, you only need to specify the file paths to the Path or LiteralPath parameters.

For example, let’s delete two files. The below command deletes the files whose paths are contained in the $files variable.

$files = @( 
'C:\temp\logs\0ndx7grg.txt', 
'C:\temp\logs\2cp7981z.txt' 
) 
Remove-Item -Path $files 

# Confirm the files are deleted 
Get-ChildItem -Path $files

PowerShell Delete Files Matching a Pattern

Pattern matching is useful when you want to delete files that match a specific extension, has a specific character in the filename, or all files at once.

PowerShell Delete All Files in Folder

The command below deletes every file inside the C:\temp\logs folder. The folder contains ten files consisting of five .TXT and five .XML files.

In this example, let’s append the -WhatIf switch to see which files will be deleted without actually deleting the files.

Remove-Item -Path C:\temp\logs\*.* -WhatIf

When you’re happy with the intended result, you can remove the -WhatIf switch to delete the files permanently.

PowerShell Delete All Files in Folder with Filter

Suppose you only want to delete files matching *.txt filename extension but exclude those containing 0 in their filenames. You can use the -Include and -Exclude parameters in this example.

First, let’s list all the *.txt files in the folder. This step is optional and is only needed if you want to compare the list of existing files and the list of files to delete.

Get-ChildItem C:\Temp\logs\*.txt

Next, run the below command to delete the *.TXT files but exclude the files containing the character 0 in the filename.

Remove-Item -Path C:\temp\logs\* -Include *.txt -Exclude "*0*" -WhatIf

PowerShell Delete Files in Folder Recursively

You can delete all files recursively without deleting the folders and subfolders. Run the command below to list all files under the c:\temp\logs directory.

(Get-ChildItem -File -Path C:\temp\logs -Recurse).FullName

Based on the result below, there are ten files, five subfolders containing one file each.

Now, let’s pipe the same command to the Remove-Item cmdlet to delete all the files.

(Get-ChildItem -File -Path C:\temp\logs -Recurse).FullName | Remove-Item -WhatIf

As you can see, the Remove-Item cmdlet will only delete the files and not the subfolders.

PowerShell: How to Delete Folder and Subfolders?

What if you want to delete not just the files but the entire folder structure?

This first command deletes the contents and subfolders but leaves the parent folder C:\temp\logs.

# Delete subfolders and contents 
Remove-Item -Path C:\temp\logs\* -Recurse -WhatIf

This next command deletes the top folder C:\Temp\logs and all subfolders.

# Delete top folder, subfolders, and contents 
Remove-Item -Path C:\temp\logs -Recurse -WhatIf

Delete Old Files Through PowerShell

Say you have a script or task that creates a backup of logs or objects to file. In most cases, you must limit the backup age, or the accumulated size will eventually consume the free disk space.

For example, the below command gets all files older than seven days. You can change the $ageInDays value to adjust the threshold as needed.

# Get the date and time now. 
Get-Date 

# Set the threshold 
$ageInDays = 7 

# Get all files older than $ageInDays 
$filesToDelete = Get-ChildItem -File -Path C:\temp\logs\* | ` 
Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$ageInDays) } 

# List the files to delete 
$filesToDelete | Select-Object FullName, CreationTime

Now that you have the list of files to delete let’s pipe the list to the Remove-Item cmdlet.

($filesToDelete).FullName | Remove-Item -Verbose

PowerShell: Delete Large Files

Another variation of housekeeping is deleting files based on size. Consider 1.5GB as large, and you want to make sure you delete such large files using PowerShell to maintain the disk space usage.

First, in this example, let’s list all files larger than a specific size, such as 1.5GB.

# Set the file size threshold. Any file larger than this will be deleted. 
$sizeThreshold = 1.5GB 

# Get all files larger than $sizeThreshold 
$filesToDelete = Get-ChildItem -File -Path C:\temp\logs\* | ` 
Where-Object { $_.Length -gt $sizeThreshold } 

# List the files to delete 
$filesToDelete | Select-Object FullName, Length

In this example, there’s one file larger than 1.5GB.

Finally, pipe the $filesToDelete variable to the Remove-Item cmdlet.

# Delete the files 
($filesToDelete).FullName | Remove-Item -Verbose

Conclusion

Deleting files is part of the typical maintenance to ensure there’s enough free disk space for your servers. The Remove-Item and Get-ChildItem combination is all you need to create a PowerShell script to delete files and folders, which you can run at a schedule.

Remember, deleting files and folders in PowerShell will permanently delete those items and will not be found in the Recycle Bin. So, test your Remove-Item commands with the WhatIf switch first to ensure you’re deleting the correct items and avoid accidental data loss.



This post first appeared on GadgetRevo.com, please read the originial post: here

Share the post

How to Use PowerShell to Delete Files and Folders?

×

Subscribe to Gadgetrevo.com

Get updates delivered right to your inbox!

Thank you for your subscription

×