Reputation: 10474
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.
Upvotes: 7
Views: 15036
Reputation: 1
For those who are interrested in, this post help me a lot and I found that 2 steps are needed: first "does the source exists?", and second "is it linked to the log I'll use with?".
So:
[System.Diagnostics.EventLog]::SourceExists($yourSource)
[System.Diagnostics.EventLog]::LogNameFromSourceName($yourSource,".")
Where "."
refers to the running computer (localhost)
Upvotes: 0
Reputation: 27852
There seems to be some confusion between an EventLog and an EventLogSource.
Here is my example: (with strict-mode ON)
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 ""
}
Upvotes: 0
Reputation: 815
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"
Upvotes: 3
Reputation: 7625
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
Upvotes: 4