Delete Windows Event Logs With PowerShell Script

PowerShell! I don't know how you feel when you hear this. For me, there is a small story behind this. I heard this back in 2014 when I was in 2nd year of my graduation. One of my colleague asked the faculty “Sir! What is PowerShell?” He replied, “It is just a blue color cmd used for higher security purpose”. After this reply, no one dared to ask any further questions. I never took any interest knowing more about it. But the things got changed since i got my first job as Windows Administrator. Being new to the environment I used to get some boring kind of stuff like clearing C drive junks files on the servers. So, Every time I logged on the servers and cleared the unwanted files, manually. Seriously, it was a time consuming job and the main thing is that there was no fun in doing this.

I did the same thing for two months unless I came in touch with a great person “Jatin Purohit”. Jatin has good scripting skills in PowerShell and So, I got inspired by him. PowerShell can change the way you think to work.

delete-event-logs-with-powershell

Download Script 29 downloads

Little about Windows Event Logs

The event logs capture the events that happen on your computer by tracing the activities done by program or user. Windows server logs consist of Windows logs and Applications and Services logs with .evtx or .evt file extension.

How Event Logs can help us

If this log is configured properly, you can manage the logs more efficiently and can use that information effectively. But the condition can go even worse if it not. It can impact your server performance by occupying a huge space in Gigs on the disk. Sometimes, your system C drive can run out of the disk and can result in slowness. In that case, you will have to delete the logs file which is older and not important to your system

So, Here We go….

To delete the event logs files we are going to use these three cmdlet.
  1. Get-ChildItem
  2. Where-Object
  3. Remove-Item

Get-ChildItem : We use this cmdlet to get the directories, subdirectories, and files In a file system drive.

Eg : Type Get-ChildItem on your poweshell console and it will return the default display lists the mode (attributes), last write time(of file), file size (length), and the name of the file. The valid values for mode are d (directory), a (archive), r (read-only), h (hidden), and s (system).

We will be using LastWriteTime attribute to filter the older logs.

PS C:\Rohit> Get-ChildItem

Get-ChildItem

Where-Object : This cmdlet help us to filter the data returned by the other cmdlet. It acts like where statement. The '?' symbol and Where are both aliases for Where-Object. It is much helpful in selecting the files which were created after certain date or selecting the events with particular ID.

Why we use Pipeline(|) :

Its main job is to join two statements so that the output of the first clause, becomes the input of the second clause. Cmd-let1 | Cmd-let1

For example we have some files with different date in the Rohit Directory

Files Name example

Now we will filter the file where type equals to Zero

PS C:\Rohit> Get-ChildItem | Where-Object {$_.Length -eq 0 }

Where-Object

Remove-Item : This cmdlet deletes one or more items, including files, folders, registry keys, variables, aliases, and functions. It can also passed with different cmdlet via pipeline (|)

PS C:\Rohit> Get-ChildItem (to list the file);

PS C:\Rohit> Get-ChildItem | Remove-Item

Remove-Item

Script to delete event logs

Lets use all that three cmdlets altogether to create a simple script that will delete the Event logs older than 15 days.

$Path,$Time are variables that contains the location of event logs and the specific date duration for file deletion. We can also pass it directly instead of creating variables.

-Recurse will access all the files and subfolder files.

-Force will Override restrictions that prevent the command from succeeding.That means will override a files read-only attribute, but will not change file permissions.

-ErrorAction SilentlyContinue To control how your script responds to nonterminating errors, It will surpass the error messages that will be generated if any error occurs .

$Path ="C:\Windows\System32\winevt\Logs";
$Time = (Get-Date).Adddays(-15);
Get-ChildItem -Path $Path -Recurse -Force | `
Where-Object {$_.LastWriteTime -lt $Time } | `
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

If you want to configure this script for remote servers. Just change the $Path variable value with

\\ServerName\C$\Windows\System32\winevt\Logs

Let create a Script to delete windows event logs for N no. of servers

We will use a text file lets say Servers.txt that will contains our lists of servers and we will use import the list of servers from Servers.txt to our script.

Using Get-Content –Path "Server.txt";


$ServersList=Get-Content -path servers.txt

Write-Host "Script has the started task";
foreach($Computer in $ServersList) {

$Computer=$Computer.Trim(); #To remove spaces from right and left side

if($Computer) {

Write-Host "Script is working on " $Computer

$Path ="C:\Windows\System32\winevt\Logs";
$Time=(Get-Date).Adddays(-15); #No. of days older (-days)

Get-ChildItem -Path $Path -Recurse -Force | `
Where-Object {$_.LastWriteTime -lt $Time } | `
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

               }

                                    }

Write-Host "Script has finished the task";


We can also create a user-defined function for the same task

user defined function is nothing but no. of codes written to perform a task under a custom namespace eg: Delete-EventLogs or Delete-MyLogs

Param([String]$Path,[String]$Computer,[String]$Time)

Param mean Parameter and $Path,$Computer, $Time are the variable in which we will pass the value while calling the function


function Delete-EventLogs   {  #Creating function by name Delete-EventLogs

Param([String]$Path,[String]$Computer,[String]$Time)
if (Test-Path $Path) {
Write-Host "Script is working on " $Computer
Get-ChildItem -Path $Path -Recurse -Force | `
Where-Object {$_.LastWriteTime -lt $Time } | `
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

                      }


                            }

 

Writing rest of codes and configure the variable.


$ServersList=Get-Content -path "servers.txt" #Importing list of servers

#Setting path for remote server
$Path ="\\" + $Computer + "\c$\Windows\System32\winevt\Logs"

#Adding time (-15)days for 15days older files.
$Time=(Get-Date).Adddays(-15);

#Calling each server one by one by using foreach loop
foreach($Computer in $ServersList) { #Fetching one server at a time.

$Computer=$Computer.Trim(); #Removing space from right and left.

#checking if $Computer variable is not empty
if($Computer) {

#calling function passing path value  computer name     ime for deletion
Delete-EventLogs  -Path $WinEvtLogs -Computer $Computer -Time $time

               }

                                       }




People Reaction : 1

Rohit Sharma
Name : Email : Website :
Rohit Sharma

Hi There! My name is Rohit and I am working in the one of MNC as Web Apps developer. I have been in this tech industry for last 3.6 years. This blog is just a part of my career journey.
Ready to make new mistakes without repeating the previous ones.

"All life is an experiment. The more experiments you make the better"


© 2020 WriteSomeCode. All Right Reserved. A Rohit Sharma Blog. Creative Commons License licensed under a Creative Commons Attribution 4.0 International License