How to clear a event log in Powershell 7

Viewed 717

in Powershell 5 we can clear a Windows-Event-Log in this way:

Get-EventLog -LogName * | % { Clear-EventLog -LogName $_.log }

how to do this in Powershell 7??? (using powershell only)

Powershell way of handling windows events is now with Get-WinEvent
but it appears no Clear-WinEvent is available

of course we can do this with wevtutil.exe
or even brute-forcing the logs file deletion after stopping the service...
but i'm asking only with native powershell code.

1 Answers

Well this is interesting. Clear-WinEvent indeed is not part of PowerShell 7. There was an issue raised to get it added but doesn't like that's going anywhere without more action.

The Microsoft approved way to do this is:

Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShell
Get-EventLog -LogName * | % { Clear-EventLog -LogName $_.log }

This spins up a Windows PowerShell 5.1 process that runs in the background and invokes the Cmdlet via implicit remoting... not the best.

A better way would be to leverage the .NET EventLogSession.ClearLog method:

Get-WinEvent -ListLog * | foreach {
    [System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.ClearLog($_.LogName)
}

Aside - PowerShell 7 module compatibility lists the Microsoft.PowerShell.Management module (that Get-EventLog and Clear-EventLog are part of) as 'Built into PowerShell 7'

Related