Remove files using PowerShell function Remove-Item.

Remove files by using PowerShell will be much easier than doing it manually. By using the below function in PowerShell we can delete files and folders.


To Remove specific folder one should provide the specific path.

Note: It will delete all the child items which exist in the specific folder.

Remove-Item -Path "//Server1/TestFolder" -recurse

I will explain 2 scenarios in this post, where we can make use of this Remove-Item function properly.

Scenario 1 for Remove files :

Files need to delete regularly which got created more than 180 days, We need to delete only files, not folders.


$root = '\\Server\backups'
$limit = (Get-Date).AddDays(-8)
Get-ChildItem $root -Recurse * | ? {-not $_.PSIsContainer -and $_.CreationTime -lt $limit} | Remove-Item

If we need to include folder also, Just remove PSIsContainer condition.


Scenario 2 for Remove files:

Files need to be deleted but we need to track which all files got deleted.

$Path = '\\Server\backups'
$limit = (Get-Date).AddDays(-180)
$files=Get-ChildItem -Path $Path| where-object { -not $_.PSIsContainer -and $_.CreationTime -lt $limit}
foreach( $file in $files.FullName)
Remove-Item -Path $file 
write-host "$file got deleted on $Time"

)|Out-file -FilePath "C:\PowerShell\RemoveItems\OutPut.txt"


The above script will delete all the files which are created more than 180days and will give the which files got deleted as output.

Remove files
We can create Job in SQL Server and schedule to run the Script according to over requirement.

Note: To learn more about Remove-Item function, Please click below link.
Click Me




Add a Comment

Your email address will not be published. Required fields are marked *