Need help with "ManagementObjectSearcher"

 This is what I am trying to do. Search the EventLog (System log) to see what datetime a log was written. It is just the logs for the Start and stop time of the Event Log Service.

I am not sure what values I need to enter for the foreach statements. To get the most recent date/time value


       try
         {
            string sQueryStart = "select * from Win32_NTLogEvent where SourceName= Event Log and EventCode= 6005";
            string sQueryStop = "select * from Win32_NTLogEvent where SourceName= Event Log and EventCode= 6006";
      
            ManagementObjectSearcher LogStartSearcher = new
               ManagementObjectSearcher(sQueryStart);      

            ManagementObjectSearcher LogStopSearcher = new
               ManagementObjectSearcher(sQueryStop);      

            ManagementObjectCollection LogStartCollection = LogStartSearcher.Get();
            ManagementObjectCollection LogStopCollection = LogStopSearcher.Get();
           
            foreach (ManagementObject Item in LogStartCollection)
            {
               //Need to search through these and get the most recent
               //entry that was written. Will need just DateTime written


            }
            foreach (ManagementObject Item in LogStopCollection)
            {
               //Need to search through these and get the most recent
               //entry. Will need just DateTime written

            }
         }
         catch (Exception e)
         {
            System.Diagnostics.EventLog.WriteEntry(this.ToString(),
               ERROR.FAILED_TO_DETERMINE_EVENT_LOG_SERVICE_DATE_TIME + e.ToString() + " Stack Trace: "
               + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
         }
LVL 2
NewMom2BrandonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
I could imagine something more like this:


         try
         {

             string sQuery = "Select * From Win32_NTLogEvent Where SourceName='Event Log' And EventCode=6005 Or
                 EventCode=6006";
     
            ManagementObjectSearcher LogSearcher = new
               ManagementObjectSearcher(sQuery);

            foreach (ManagementObject Item in LogSearcher.Get())
            {

               //Need to search through these and get the most recent
               //entry that was written. Will need just DateTime written
              string code = Item.Properties("EventCode").ToString();

              bool isStart = (code == "6005");

            }
         }
         catch (Exception e)
         {
            System.Diagnostics.EventLog.WriteEntry(this.ToString(),
               ERROR.FAILED_TO_DETERMINE_EVENT_LOG_SERVICE_DATE_TIME + e.ToString() + " Stack Trace: "
               + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
         }

Bob
Bob LearnedCommented:
I could imagine something more like this:


         try
         {

             string sQuery = "Select * From Win32_NTLogEvent Where SourceName='Event Log' And EventCode=6005 Or
                 EventCode=6006";
     
            ManagementObjectSearcher LogSearcher = new
               ManagementObjectSearcher(sQuery);

            foreach (ManagementObject Item in LogSearcher.Get())
            {

               //Need to search through these and get the most recent
               //entry that was written. Will need just DateTime written
              string code = Item.Properties("EventCode").ToString();

              bool isStart = (code == "6005");

            }
         }
         catch (Exception e)
         {
            System.Diagnostics.EventLog.WriteEntry(this.ToString(),
               ERROR.FAILED_TO_DETERMINE_EVENT_LOG_SERVICE_DATE_TIME + e.ToString() + " Stack Trace: "
               + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
         }

Bob
NewMom2BrandonAuthor Commented:
I actually need the times of both the start and the stop.  So I can compare the two later to see if they are close in time. If they are then I know a proper shutdown was performed.

If the stop time is missing or not close then I know a proper shutdown was not performed or the PC has been turned off for a while

Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

NewMom2BrandonAuthor Commented:
I got it to give me both the start and stop times but it is being written out like this...So the description I need to change into a date and time format

Event Type:      Information
Event Source:      Made it to Log Start
Event Category:      None
Event ID:      0
Date:            7/7/2005
Time:            3:22:15 PM
User:            N/A
Computer:      QG050892
Description:
20050628074811.000000-300

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

here is what I did

         try
         {
            string sQueryStart = "select * from Win32_NTLogEvent where SourceName= 'eventlog' and EventCode= '6005'";
            string sQueryStop = "select * from Win32_NTLogEvent where SourceName= 'eventlog' and EventCode= '6006'";
      
            ManagementObjectSearcher LogStartSearcher = new
               ManagementObjectSearcher(sQueryStart);      

            ManagementObjectSearcher LogStopSearcher = new
               ManagementObjectSearcher(sQueryStop);      

            ManagementObjectCollection LogStartCollection = LogStartSearcher.Get();
            ManagementObjectCollection LogStopCollection = LogStopSearcher.Get();
           
            foreach (ManagementObject Item in LogStartCollection)
            {
               //Need to search through these and get the most recent
               //entry that was written. Will need just DateTime written
               string DMTF = Item.Properties["TimeWritten"].Value.ToString();
//               DateTime dLogStartDateTime = Convert.ToDateTime(DMTF);
//               DateTime dLogStartDate = Convert.ToDateTime(DMTF).Date;

               string sTest = DMTF.ToString();

               System.Diagnostics.EventLog.WriteEntry("Made it to Log Start ", sTest);

            }

            foreach (ManagementObject Item in LogStopCollection)
            {
               //Need to search through these and get the most recent
               //entry. Will need just DateTime written

               string DMTF = Item.Properties["TimeWritten"].Value.ToString();
//               DateTime dLogStopDateTime = Convert.ToDateTime(DMTF);
//               DateTime dLogStopDate = Convert.ToDateTime(DMTF).Date;
               string sTest = DMTF.ToString();

               System.Diagnostics.EventLog.WriteEntry("Made it to Log Stop ", sTest);

            }
            LogStartSearcher.Dispose();//Release resources
            LogStopSearcher.Dispose();//Release resources
         }
         catch (Exception e)
         {
            System.Diagnostics.EventLog.WriteEntry(this.ToString(),
               ERROR.FAILED_TO_DETERMINE_EVENT_LOG_SERVICE_DATE_TIME + e.ToString() + " Stack Trace: "
               + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
         }

NewMom2BrandonAuthor Commented:
I got it to give me both the start and stop times but it is being written out like this...So the description I need to change into a date and time format

Event Type:      Information
Event Source:      Made it to Log Start
Event Category:      None
Event ID:      0
Date:            7/7/2005
Time:            3:22:15 PM
User:            N/A
Computer:      
Description:
20050628074811.000000-300

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

here is what I did

         try
         {
            string sQueryStart = "select * from Win32_NTLogEvent where SourceName= 'eventlog' and EventCode= '6005'";
            string sQueryStop = "select * from Win32_NTLogEvent where SourceName= 'eventlog' and EventCode= '6006'";
      
            ManagementObjectSearcher LogStartSearcher = new
               ManagementObjectSearcher(sQueryStart);      

            ManagementObjectSearcher LogStopSearcher = new
               ManagementObjectSearcher(sQueryStop);      

            ManagementObjectCollection LogStartCollection = LogStartSearcher.Get();
            ManagementObjectCollection LogStopCollection = LogStopSearcher.Get();
           
            foreach (ManagementObject Item in LogStartCollection)
            {
               //Need to search through these and get the most recent
               //entry that was written. Will need just DateTime written
               string DMTF = Item.Properties["TimeWritten"].Value.ToString();
//               DateTime dLogStartDateTime = Convert.ToDateTime(DMTF);
//               DateTime dLogStartDate = Convert.ToDateTime(DMTF).Date;

               string sTest = DMTF.ToString();

               System.Diagnostics.EventLog.WriteEntry("Made it to Log Start ", sTest);

            }

            foreach (ManagementObject Item in LogStopCollection)
            {
               //Need to search through these and get the most recent
               //entry. Will need just DateTime written

               string DMTF = Item.Properties["TimeWritten"].Value.ToString();
//               DateTime dLogStopDateTime = Convert.ToDateTime(DMTF);
//               DateTime dLogStopDate = Convert.ToDateTime(DMTF).Date;
               string sTest = DMTF.ToString();

               System.Diagnostics.EventLog.WriteEntry("Made it to Log Stop ", sTest);

            }
            LogStartSearcher.Dispose();//Release resources
            LogStopSearcher.Dispose();//Release resources
         }
         catch (Exception e)
         {
            System.Diagnostics.EventLog.WriteEntry(this.ToString(),
               ERROR.FAILED_TO_DETERMINE_EVENT_LOG_SERVICE_DATE_TIME + e.ToString() + " Stack Trace: "
               + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
         }

Bob LearnedCommented:
I am just playing the devil's advocate :)

I still don't see why you need the two loops, and not the one with the criteria for getting both the start and stop times (EventCode=6005 Or EventCode=6006).

Bob
NewMom2BrandonAuthor Commented:
I can use one loop but I would need to do a And not an or...

becasue both will be present if the machine was shutdown correctly.  and or will just give me one or the other correct.

Right now I am getting back a long string 20050628074811.000000-300 which I need to have changed into a dateTime value

I am planning on switching it into a one loop but I just wanted to get it working for now. I have to make it so I only get the ones for today and the most recent time yet.

I have been doing some thinking though. I am wondering if using WinLogon would be a better way to track this. WinLogon I think will actually tell me if the PC was hibernated, Shutdown, restarted and safe or unsafe..I think
Bob LearnedCommented:
Trying to make sure that I completely understand this:

Are there 2 entries--1 for start and 1 for stop?

If so, then loop through all events that apply to a specific event log and are either a stop event or a start event.

If this is a valid assessment of your requirement, then you can understand why I recommend the Or, and not the And.

Bob
NewMom2BrandonAuthor Commented:
There are two entries..

One for Start and one for Stop. Shown below...

Event Type:      Information
Event Source:      EventLog
Event Category:      None
Event ID:      6005
Date:            7/6/2005
Time:            12:36:51 PM
User:            N/A
Computer:      
Description:
The Event log service was started.

and

Event Type:      Information
Event Source:      EventLog
Event Category:      None
Event ID:      6006
Date:            7/6/2005
Time:            12:27:27 PM
User:            N/A
Computer:      
Description:
The Event log service was stopped.

When you shutdown your computer the EventLog is triggered to Stop. So the "Event Log stop" is added to the System log. However when the PC is shutdown by "HardShutdown" Just clicking the power button the stop is not triggered. So no Event Log Stop is added to the System Log. As soon as the PC restarts then the "Event Log start" is added to the System Log.

Then my service starts, becasue it starts as soon as the PC does. It checks and notices that a shutdown has happened by a previous WMI search for System bootup time. Then it will get the Start and Stop times of the Event Log Service (by seeing the time written for the start and stop of the event log service( as shown above)). It will compare the two times to see that they are within a couple of minutes of each other or not and send an email out saying the PC was shutdown correctly or not.

If the or is still a good reason based on what I mention above then I will give it a shot.
Bob LearnedCommented:
IMHO, I believe that the 'Or' is what you need here.

Do you have an idea of how to associate the start event with the stop event, or do you need help with that, too.

Bob
NewMom2BrandonAuthor Commented:
I think I am going to need a little help...

right now I have been trying to get the following...

Information receiving back: 20050628074811.000000-300
Information I only need so I can switch it to a dateTime: 20050628074811  So every thing from the "." and to the right can be removed.

I am not sure how to do a within a couple of minutes of each other...
NewMom2BrandonAuthor Commented:
Ok stupid question what is IMHO?
Bob LearnedCommented:
Not a stupid question.

IMHO = in my humble opinion.

Internet slang reference:
http://www.byteshift.de/web-design-Internet_slang-en

Convert text to DateTime:

      string text = "20050628074811.000000-300";

      text = text.Substring(0, text.IndexOf('.'));

      DateTime dt = DateTime.ParseExact(text, "yyyyMMddhhmmss", CultureInfo.InvariantCulture, DateTimeStyles.None);

            Result = "6/28/2005 7:48:11 AM"

Bob

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
NewMom2BrandonAuthor Commented:
Once again...thank you Bob!!!!!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.