How to determine if an EventLog already exists

筅森魡賤 提交于 2019-12-03 22:05:29
# Check if Log exists
# Ref: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.exists(v=vs.110).aspx
[System.Diagnostics.EventLog]::Exists('Application');


# Ref: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.sourceexists(v=vs.110).aspx
# Check if Source exists
[System.Diagnostics.EventLog]::SourceExists("YourLogSource");

So I was on the right path with Get-EventLog.

Instead of just reading it, I stored it in a variable. Then I checked if the variable was null.

This has achieved what I was looking to do.

$logFileExists = Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Visual Studio Builds"} 
if (! $logFileExists) {
    New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio"
}

if ([System.Diagnostics.EventLog]::SourceExists("Visual Studio") -eq $False) { New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio" }

Shay Levy

Check the Exists method:

[System.Diagnostics.EventLog]::Exists('Visual Studio Builds')

To simply check if exists:

$EventLogName = "LogName"
if ( !($(Get-EventLog -List).Log.Contains($EventLogName)))
{}

But to create the new one you'll need "As Administrator" privilege. To solve this I used to call a subprocess:

Start-Process -verb runAs powershell.exe  -ArgumentList "-file $PSScriptRoot\CreateLog.ps1" -wait

With simple CreateLog.ps1:

New-EventLog -LogName ScriptCheck -Source ScriptCheck
Write-EventLog –LogName ScriptCheck `
–Source ScriptCheck –EntryType Information –EventID 100 `
–Message "Start logging!"

I think below approach could reduce the workload of filter with where

    try
    {
        Get-EventLog -LogName "Visual Studio Builds" -ErrorAction Ignore| Out-Null
    }
    catch {
        New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio"
    }

Less complex:

 if (!(Get-Eventlog -LogName "Application" -Source "YourLog")){
      New-Eventlog -LogName "Application" -Source "YourLog"
 }
$SourceExists = [System.Diagnostics.Eventlog]::SourceExists("XYZ")
if($SourceExists -eq $false){
    [System.Diagnostics.EventLog]::CreateEventSource("XYZ", "Application")
}

Just doing this is not enough. Even though you've created the event source, $SourceExists will always be false. I tested it also by running CreateEventSource then Remove-EventLog, and removing it failed. After creating an event source, you must write something to it. Append this after running CreateEventSource.

Write-EventLog -LogName "Application" -Source "XYZ" -EventID 0 -EntryType Information -Message "XYZ source has been created."

Thanks to https://stackoverflow.com/users/361842/johnlbevan pointing this out (in the comments).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!