File Remover Script

Here is a little file remover script I wrote for servers here. It takes either takes 2 arguments or can be run interactively. It looks in a directory specified and removes the files that are x days old. This is nice for servers that fill up with backup files or logs. This goes hand-in-hand with volume size monitoring, of course. Feel free to use/change or comment on the script. Enjoy!

  1. /*
  2. * File Remover Program
  3. * Author: Mike Dunphy
  4. * Seattle Pacific University
  5. * Description: This program either takes 2 arguments or can be run interactively. The two arguments are 1. path
  6. * where files are to prune and 2. how many days back to delete files
  7. */
  8.  
  9.  
  10.  
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Text;
  14. using System.IO;
  15.  
  16. namespace fileRemover
  17. {
  18. class Program
  19. {
  20. static void Main(string[] args)
  21. {
  22. string path = null;
  23. string days = null;
  24. if (args.Length > 0)
  25. {
  26. if (args.Length == 2)
  27. {
  28. path = args[0].ToString();
  29. days = args[1].ToString();
  30. }
  31. else
  32. {
  33. Console.WriteLine("Please enter 2 arguments - Path and days to prune");
  34. System.Environment.Exit(777);
  35. }
  36. }
  37. else
  38. {
  39. Console.Write("Enter path to prune: ");
  40. path = Console.ReadLine();
  41. Console.Write("Enter days back to prune: ");
  42. days = Console.ReadLine();
  43. }
  44. string formattedDate;
  45. formattedDate = DateTime.Now.AddDays(-30).ToString("yyyyMMdd");
  46. if (path != null && days != null)
  47. {
  48. DirectoryInfo di = new DirectoryInfo(path);
  49. FileInfo[] fis = di.GetFiles();
  50.  
  51. foreach (FileInfo fi in fis)
  52. {
  53. if (fi.LastWriteTime < DateTime.Now.AddDays(-Int32.Parse(days)))
  54. {
  55. fi.Delete();
  56. }
  57. }
  58. }
  59. else
  60. {
  61. Console.WriteLine("Something went seriously wrong. Program takes 2 arguments or is run interactively. Fail.");
  62. System.Environment.Exit(777);
  63. }
  64. }
  65. }
  66. }