1

I have a server that continues to close the gap on our D: Storage. So, from time to time I go into the location and manually delete files to free some space "Yuck". I have created a simple Powershell script that allows me to configure which files specifically and the dates (this is important) that need to be removed. Unfortunately during my testing, I soon realized the files are permanently deleted and I would rather have them sent to the Trash bin.

Here is the code:

   Get-ChildItem -Recurse C:\Temp\TWLogTest\*.* | Where-Object {$_.CreationTime -gt (get-date "12-03- 2016 01:00AM") -and $_.
   CreationTime -lt (get-date "10-10-2019 14:00PM")} | Where-Object {$_.name -match "tomcat"} | Remove-Items

Any help, guidance or ideas with implementing a Delete into this specific script would be greatly appreciated. I have looked at Module-Recycle, but still not sure how to add it here.

Thanks, Matt

Matthew
  • 15
  • 5
  • But if the goal is to free disk space, recycling won't help. – Bill_Stewart Nov 12 '19 at 21:16
  • This is true and thanks for your input, I figured it would free space on that specific drive and allow flexibility in case of deleting the wrong file. These are application logs they may hold data. – Matthew Nov 12 '19 at 21:27

1 Answers1

2

Based on here: How do I move a file to the Recycle Bin using PowerShell?

using assembly microsoft.visualbasic
using namespace microsoft.visualbasic

[FileIO.FileSystem]::DeleteFile('foo.txt', 'OnlyErrorDialogs', 'SendToRecycleBin')

Something like this should match your code. That method only works on files. When comparing dates, the 2nd argument will get cast to [datetime] anyway.

using assembly microsoft.visualbasic
using namespace microsoft.visualbasic

Dir -File -R C:\Temp\TWLogTest | Where { 
  $_.CreationTime -gt '12/3/16 1AM' -and 
  $_.CreationTime -lt '10/10/19 2PM' -and 
  $_.name -match 'tomcat' } | 
foreach { [FileIO.FileSystem]::DeleteFile($_.fullname, 'OnlyErrorDialogs',
  'SendToRecycleBin') }
js2010
  • 23,033
  • 6
  • 64
  • 66
  • Right, I have seen this solution and it probably works well with short file names, the problem is the data logs have long names and dates attached to them... I cannot use 'foo.txt' (i get it as an example) because the file names require more specificity. This is why I used " -match 'tomcat' " because tomcat is a word within certain files I need to remove. – Matthew Nov 13 '19 at 14:54
  • Worked like a charm. Awesome stuff, thanks for the helpful implementation ! – Matthew Nov 13 '19 at 21:06