Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if event log with certain source name exists?

Tags:

powershell

We want to check if a log with a certain source name exists. The log is created as follows:

New-EventLog -LogName Application -Source "MyName"

Now we want to use a PowerShell function to check it this log exists. A working solution is the following:

[System.Diagnostics.EventLog]::SourceExists("MyName") -eq $false

which returns False if the log exists and true if it does not.

How can we make this code so that it makes use of PowerShell's built in features instead of the .NET classes? We tried code from here:

$sourceExists = !(Get-EventLog -Log Application -Source "MyName")

but it returns a GetEventLogNoEntriesFound exception.

Can someone help us out? Thanks.

like image 331
Erwin Rooijakkers Avatar asked Jan 28 '15 15:01

Erwin Rooijakkers


2 Answers

The correct way is, pretty much the same as above:

function Test-EventLogSource {
Param(
    [Parameter(Mandatory=$true)]
    [string] $SourceName
)

[System.Diagnostics.EventLog]::SourceExists($SourceName)
}

Then run:

Test-EventLogSource "MyApp"
like image 68
Phil Avatar answered Nov 08 '22 23:11

Phil


You could wrap that in a Cmdlet as follows:

function Test-EventLog {
    Param(
        [Parameter(Mandatory=$true)]
        [string] $LogName
    )

    [System.Diagnostics.EventLog]::SourceExists($LogName)
}

Note: You will need to run this script from an elevated PowerShell console (Run as Admin) for it to work:

Test-EventLog "Application"
True
like image 41
oɔɯǝɹ Avatar answered Nov 08 '22 22:11

oɔɯǝɹ