简体   繁体   中英

Powershell get eventlog source

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?

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 }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM