Tuesday, November 06, 2018

Create New Event Log Source

Create a new console app and then paste this code. The resulting exe must be run as administrator, and you need to pass in the name of the source. You probably will want to create a cmd or bat file to run the exe.


using System;
using System.Diagnostics;

namespace CreateEventLogSource
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 1 && !String.IsNullOrWhiteSpace(args[0]))
            {
                string eventSource = args[0];
                if (EventLog.SourceExists(eventSource))
                {
                    Console.WriteLine("Event Log Source already exists");
                }
                else
                {
                    // No exception yet means the user has admin privileges
                    try
                    {
                        EventLog.CreateEventSource(eventSource, "Application");
                        Console.WriteLine("Event log source created.");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("An exception occurred during CreateEventSource. Details follow.");
                        Console.WriteLine(ex);
                        return;
                    }

                    try
                    {
                        EventLog.WriteEntry(eventSource, "Test", EventLogEntryType.Information);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("An exception occurred during WriteEntry. Details follow.");
                        Console.WriteLine(ex);
                        return;
                    }
                }
            }
            else
            {
                Console.WriteLine("You must pass in the name of the Event Log Source");
            }
        }
    }
}