Tuesday 8 July 2014

Clear Event Logs After Certain Time

The below script will export all of the events in event viewer excluding the last two hours.  Then will reimport.  You can update the hours to clear to be whatever you want.  This is useful when you need to cover your tracks. 

Open powershell as an administrator (THIS IS IMPORTANT)


#Remove Traces
$remove = $true
#Temporary Work Directory.
$tempdir = "C:\temp"
 
#How Many Hours of logs do you want to clear. Type '-2' for two hours
$hourstoclear = "-2"

#Start time
$start = (get-date).addhours($hourstoclear)
 
#Get Event locations
$secloc = (Get-ItemProperty -Path HKLM:System\Controlset001\services\Eventlog\Security -name "File").file
$apploc = (Get-ItemProperty -Path HKLM:System\Controlset001\services\Eventlog\Application -name "File").file
$sysloc = (Get-ItemProperty -Path HKLM:System\Controlset001\services\Eventlog\System -name "File").file
function GetMilliseconds ($date) {
    $ts = New-TimeSpan -Start $date -End (Get-Date)
    [math]::Round($ts.TotalMilliseconds)
    } # end function
$startDate = GetMilliseconds(Get-Date $start)
#Export Results to EVTX
wevtutil epl Security $tempdir\Security.evtx /q:"*[System[TimeCreated[timediff(@SystemTime) >= $startDate]]]"
wevtutil epl Application $tempdir\Application.evtx /q:"*[System[TimeCreated[timediff(@SystemTime) >= $startDate]]]"
wevtutil epl System $tempdir\System.evtx /q:"*[System[TimeCreated[timediff(@SystemTime) >= $startDate]]]"
$procid = (Get-WmiObject Win32_Process -Filter "name = 'svchost.exe'" | where {$_.commandline -like "*LocalServiceNetworkRestricted*"}).processid
#Kill Event log Task
taskkill /PID $procid /F

#Copy events over.
xcopy $tempdir\Security.evtx $secloc /y
xcopy $tempdir\Application.evtx $apploc /y
xcopy $tempdir\System.evtx $sysloc /y

#Start windows event log
Get-Service "Windows Event Log" | Start-Service

#Remove exports of event logs.
if($remove -eq $true){
remove-item $tempdir\Security.evtx
remove-item $tempdir\Application.evtx
remove-item $tempdir\System.evtx
}

3 comments: