Home > Software engineering >  Powershell get eventlog source
Powershell get eventlog source

Time:02-10

Another simple question for you, which is a tough one for me... I am trying to check, if a source exist in eventlog. using this command to check:

$EventLogSource = "TestSource"
$EventLogsourceCheck = [System.Diagnostics.EventLog]::SourceExists($EventLogSource)

If the source exists, then it gives "true". The problem becomes, if the source doesn't exist. In this case the variable $EventLogsourceCheck remains the same, as it already was. in commandline i see the error:

Ausnahme beim Aufrufen von "SourceExists" mit 1 Argument(en): "Die Quelle wurde nicht gefunden, aber einige oder alle Ereignisprotokolle konnten nicht durchsucht werden. Protokolle, auf die kein Zugriff möglich war: Security." In Zeile:1 Zeichen:1

  • $tdf = [System.Diagnostics.EventLog]::SourceExists('sfdsf')
  •     CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        FullyQualifiedErrorId : SecurityException
    

i want to suppress this message and if the source doens't exist, i want the variable $EventLogsourceCheck to be false. How can i do this?

CodePudding user response:

You can suppress the errors with a Try - Catch statement, if the SourceExists method fails and throws an error, your Catch block can return $false, for example:

$ErrorActionPreference = 'Stop'
$EventLogSource = 'Application', 'System', 'SomeOtherLog'
$EventLogSource | ForEach-Object {
    [pscustomobject]@{
        LogName = $_
        SourceExists = try {
            [System.Diagnostics.EventLog]::SourceExists($_)
        } catch { $false }
    }
}
  • Related