Remove Logs

A couple of our web servers were running into some issues with disk space. Turns out the logs weren’t being cleaned up properly.
In order to remediate this, I wrote a function that can be reused anywhere.

The function accepts 3 parameters:

FilePath: The directory where you want to remove the logs from

CutOff; Specifies the age (in days) that a file must have before being deleted.

LogPath; This parameter specifies the directory where you want the CSV log file. If this is left open, no CSV will be saved.

Example

As an example, I’m going to remove all files, older than 30 days, from the folder “C:\temp\W3SVC2030036971\W3SVC2030036971\”. I want a CSV log to be written in the “C:\temp” folder.

A view from the Powershell window

As you can see, you always get feedback in your window, even if you don’t specify a log path.

The CSV looks something like this:

Code

You can find the script code below. This is provided as-is. You can find the most recent version of the code on GitHub.

PowerShell

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

#Requires -Version 3.0

FunctionRemove-Logs{

<#

.SYNOPSIS

Delete old log files

.DESCRIPTION

This function will delete all .log and .txt files older than a certain number of days.

You have the ability to specify log path, extension (log or txt) and path.

.NOTES

Author: Maarten Van Driessen

.PARAMETER FilePath

Specify the path where you want to delete the logs from.

.PARAMETER CutOff

Specify how many days you want to go back.

.PARAMETER LogPath

Where do you want to store the log file. Path must end with a \

.PARAMETER FileExtension

Specify whether you want to delete *.log, *.etl or *.txt files. If left blank, the function will delete both.

Must be written as *.log, *.etl or *.txt

.EXAMPLE

Remove-Logs -FilePath C:\inetpub\ -Cutoff 30 -LogPath c:\temp\

Delete all txt and log files older than 30 days from the c:\inetpub folder and write the log to c:\reports