1

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?

1 Answer 1

1

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 }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

using try catch works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.