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.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With