42

I'm using the following line to create a new event log

new-eventlog -LogName "Visual Studio Builds" -Source "Visual Studio"

I want to run this every time, because if I run a build from a new computer, I'd still like to see the event logs.

The problem is that every time the script is run after the log is already created, it throws an error.

New-EventLog : The "Visual Studio" source is already registered on the "localhost" computer.
At E:\Projects\MyApp\bootstrap.ps1:14 char:13
+ new-eventlog <<<<  -LogName "Visual Studio Builds" -Source "Visual Studio"
    + CategoryInfo          : InvalidOperation: (:) [New-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.NewEventLogCommand

Now I know that I can "search" for the event log

Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Visual Studio Builds"} 

But now how do I determine if it exists?

Tor
  • 1,522
  • 3
  • 16
  • 26
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
  • see also: http://stackoverflow.com/questions/28430620/only-pass-parameter-if-value-supplied - I've posted sample code for a wrapper method (though currently there's a bug - hence posting here) – JohnLBevan Feb 10 '15 at 11:34

10 Answers10

62
# 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");
Jonathan Donahue
  • 731
  • 1
  • 5
  • 2
  • 1
    This answer is the most complete in terms of checking whether both a log and/or source exist. It's important to remember that using Get-EventLog and filtering/searching from there depends on the fact that an event has been written to the target log in order for it to show up. – Daniel Cox Oct 27 '15 at 13:55
  • VERY CLEAN! Nice one-liner. – tresstylez Jan 23 '17 at 04:12
  • Thanks. You can even take off the 'system.'. – js2010 Nov 05 '19 at 15:08
26

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"
}
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
  • 4
    NB: Only works if the event log/source has been written to; if it was created but not written to you'll gen an "already exists" exception. – JohnLBevan Feb 10 '15 at 11:16
22
if ([System.Diagnostics.EventLog]::SourceExists("Visual Studio") -eq $False) {
    New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio"
}
msanford
  • 11,803
  • 11
  • 66
  • 93
Sean Webb
  • 221
  • 2
  • 3
  • 3
    We expect answer to be a little bit more verbose. Teaching how to fish is better than just spoon feed the OP. – rene Jan 06 '15 at 20:11
  • 1
    Brilliant! this is the only answer that actually checks if the source value exists & doesnt resort to scanning the event log. – Nick Kavadias Aug 26 '15 at 08:10
  • 2
    Note that this script will require local admin rights to work. Otherwise some eventlogs - such as securty - can't be accessed, resulting in a exception. The exception is thrown in both cases (true and false), so you can't determine if the log exists by catching. – omni Aug 30 '15 at 10:01
14

Check the Exists method:

[System.Diagnostics.EventLog]::Exists('Visual Studio Builds')
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
3

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!"
StanT.
  • 320
  • 2
  • 8
  • This is valid, thanks. When it comes to Admin, I do a bit different approach, I [Assert that they are Admin](https://github.com/FutureStateMobile/poshBAR/blob/master/src/poshBAR/Test-RunAsAdmin.ps1), and throw an exception if not. This forces the script to be run in an admin console before it starts. – Chase Florell Apr 09 '15 at 14:48
  • my approach is mostly intended to be used in a scheduler :) – StanT. Apr 10 '15 at 16:09
2

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"
    }
Jackie
  • 2,476
  • 17
  • 20
  • on an application with heavy workload, yes you want to optimize filtering clauses... for a script... not that much. try/catch feels icky. – Chase Florell Feb 27 '15 at 20:16
  • Chase is correct, you simply don't ever want to use exception handling as part of your logic. Jonathan Donahue's answer is the most complete in terms of checking whether both a log and/or source exist. – Daniel Cox Oct 27 '15 at 13:54
2

Less complex:

 if (!(Get-Eventlog -LogName "Application" -Source "YourLog")){
      New-Eventlog -LogName "Application" -Source "YourLog"
 }
pwrshll
  • 37
  • 1
  • Contrary to *all* intuition, [`Get-EventLog`](http://ss64.com/ps/get-eventlog.html) does **not** have a `-Source` parameter. Sorry, but -1. – jpmc26 Jul 20 '16 at 20:41
  • @jpmc26 `Get-EventLog` has indeed a `-Source` parameter. (See [official documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-eventlog)). However the proposed solution is listing actual events in the event log, so -1. – laika Jan 02 '18 at 23:19
2

This one worked for me. Hope it helps somebody.

$EventLog = "SLAPS"
If ([System.Diagnostics.EventLog]::SourceExists("$EventLog") -eq $false) {
    New-EventLog -LogName "SLAPS_PasswordRotation" -Source "$EventLog"
    Write-EventLog -LogName "SLAPS_PasswordRotation" -Source "$EventLog" -Message "EventLog Succesfully Created" -EventId 10000 -EntryType SuccessAudit
}
Else {
    Write-EventLog -LogName "SLAPS_PasswordRotation" -Source "$EventLog" -Message "New Rotation Started Succesfully" -EventId 1 -EntryType SuccessAudit
}
2

Get-/Test-EventLogSource

The System.Diagnostics methods are limiting. There can be only one source on a computer. Different computers may have the same source, but in different logs. In my experience you start running into issues after working with these methods and creating/removing logs and sources. I wrote the following to verify my custom log/source.

Set-StrictMode -Version Latest

function Get-EventLogSource {
    [CmdletBinding()]
    param(
        [string]$LogFile = '*',
        [string]$Source = '*'
    )

    Get-CimInstance -Class Win32_NTEventLOgFile -Verbose:$false | ForEach-Object {

        $_logName = $PSItem.FileName
 
        $PSItem.Sources | ForEach-Object {
 
            $oResult = New-Object PSCustomObject -Property @{
                Source  = $PSItem
                LogName = $_logName
            } | Select-Object  -Property Source, LogName

            Write-Output $oResult
        }
    } | Sort-Object -Property Source | Where-Object { $PSItem.Source -like $Source -and $PSItem.LogName -like $LogFile }    
}

function Test-EventLogSource {
    [CmdletBinding()]
    param(
        [string]$LogFile = '*',
        [Parameter(Mandatory)]
        [string]$Source
    )
    $_result = Get-EventLogSource -LogFile $LogFile -Source $Source
    return ($null -ne $_result)
}

Clear-Host

#Test-EventLogSource -LogFile 'System' -Source '.NET*' -Verbose
#Test-EventLogSource -LogFile 'Application' -Source '.NET*' -Verbose
#Test-EventLogSource -LogFile 'dummy' -Source '.NET*' -Verbose
#Test-EventLogSource -LogFile '*' -Source '.NET*' -Verbose
#Test-EventLogSource -Source '.NET*' -Verbose

#Test-EventLogSource -LogFile 'Application' -Source 'vs' -Verbose
#Test-EventLogSource -LogFile '*' -Source 'vss' -Verbose

#Test-EventLogSource -Source '*power*'


#Get-EventLogSource
#Get-EventLogSource -LogFile 'System' -Source '.NET*' -Verbose | Format-Table
#Get-EventLogSource -LogFile 'Application' -Source '.NET*' -Verbose | Format-Table
#Get-EventLogSource -LogFile 'dummy' -Source '.NET*' -Verbose | Format-Table
#Get-EventLogSource -LogFile '*' -Source '.NET*' -Verbose | Format-Table
#Get-EventLogSource -Source '.NET*' -Verbose | Format-Table

#Get-EventLogSource -LogFile 'Application' -Source 'vs' -Verbose | Format-Table
#Get-EventLogSource -LogFile '*' -Source 'vss' -Verbose | Format-Table

#Get-EventLogSource -Source '*power*'| Format-Table

Using Get-WinEvent

Get-WinEvent -ListProvider * -ErrorAction SilentlyContinue |
    Select-Object -Property Name -ExpandProperty LogLinks | 
    Select-Object -Property Name, LogName |
    Sort-Object -Property Name
AMissico
  • 21,470
  • 7
  • 78
  • 106
  • Surprised this hasn't got more votes - it's the only way I've found to code a test for the source without getting a warning about not accessing the Security logs if you;re not admin. – Scepticalist Jun 10 '22 at 06:49
0
$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).

Tyler Montney
  • 1,402
  • 1
  • 17
  • 25