How to check if an event log exists with a specific source name?

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

New-EventLog -LogName Application -Source "MyName"

Now we want to use the PowerShell function to check if this log exists. The working solution is as follows:

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

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

How can we make this code use PowerShell built-in functions instead of .NET classes? We tried the code here :

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

but returns an exception GetEventLogNoEntriesFound.

Can anybody help us? Thank.

+4
source share
3 answers

You can wrap this in the cmdlet as follows:

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

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

. script PowerShell ( ):

Test-EventLog "Application"
True
0

, , :

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

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

:

Test-EventLogSource "MyApp"
0

There seems to be some confusion between EventLog and EventLogSource.

Here is my example: (with strict ON mode)

Set-StrictMode -Version 2.0

[System.String]$script:gMyEventLogSource = 'My Source'
[System.String]$script:gEventLogApplication = 'Application'



# custom event log sources
[bool]$script:gApplicationEventLogExists = [System.Diagnostics.EventLog]::Exists($script:gEventLogApplication)

if(!$script:gApplicationEventLogExists)
{
    throw [System.ArgumentOutOfRangeException] "Event Log does not exist '($script:gApplicationEventLogExists)'"
}

Write-Host "gApplicationEventLogExists ( $script:gApplicationEventLogExists )"

[bool]$script:gMyEventLogSourceExists = [System.Diagnostics.EventLog]::SourceExists($script:gMyEventLogSource)
Write-Host "gMyEventLogSourceExists ( $script:gMyEventLogSourceExists )"
if(!$script:gMyEventLogSourceExists)
{
    Write-Host "About to create event log source ( $script:gMyEventLogSource )" 
    New-EventLog -LogName $script:gEventLogApplication -Source $script:gMyEventLogSource
    Write-Host "Finished create event log source ( $script:gMyEventLogSource )"
    Write-Host ""
}
0
source

All Articles