From 57d85d3f7e57925e24804a0a6050094c4d63c003 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Fri, 16 Jun 2017 19:23:17 +0300 Subject: [PATCH 1/2] Close eventLogSession and EventLogReader to unlock etl file --- .../GetEventCommand.cs | 495 +++++++++--------- 1 file changed, 244 insertions(+), 251 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index b13e2e76ce7..c3a68b81695 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -514,33 +514,29 @@ private void AccumulatePipelineFileNames() // private void ProcessGetLog() { - EventLogSession eventLogSession = CreateSession(); - - FindLogNamesMatchingWildcards(eventLogSession, _accumulatedLogNames); - if (_logNamesMatchingWildcard.Count == 0) + using (EventLogSession eventLogSession = CreateSession()) { - return; - } - - EventLogQuery logQuery; - if (_logNamesMatchingWildcard.Count > 1) - { - string query = BuildStructuredQuery(eventLogSession); - logQuery = new EventLogQuery(null, PathType.LogName, query); - logQuery.TolerateQueryErrors = true; - } - else - { - logQuery = new EventLogQuery(_logNamesMatchingWildcard[0], PathType.LogName, _filter); - } - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; + FindLogNamesMatchingWildcards(eventLogSession, _accumulatedLogNames); + if (_logNamesMatchingWildcard.Count == 0) + { + return; + } - EventLogReader readerObj = new EventLogReader(logQuery); + EventLogQuery logQuery; + if (_logNamesMatchingWildcard.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.LogName, query); + logQuery.TolerateQueryErrors = true; + } + else + { + logQuery = new EventLogQuery(_logNamesMatchingWildcard[0], PathType.LogName, _filter); + } + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; - if (readerObj != null) - { - ReadEvents(readerObj); + ReadEvents(logQuery); } } @@ -550,44 +546,41 @@ private void ProcessGetLog() // private void ProcessGetProvider() { - EventLogSession eventLogSession = CreateSession(); - - FindProvidersByLogForWildcardPatterns(eventLogSession, _providerName); - - if (_providersByLogMap.Count == 0) + using (EventLogSession eventLogSession = CreateSession()) { - // - // Just return: errors already written above for each unmatched provider name pattern. - // - return; - } + FindProvidersByLogForWildcardPatterns(eventLogSession, _providerName); + if (_providersByLogMap.Count == 0) + { + // + // Just return: errors already written above for each unmatched provider name pattern. + // + return; + } - EventLogQuery logQuery = null; - if (_providersByLogMap.Count > 1) - { - string query = BuildStructuredQuery(eventLogSession); - logQuery = new EventLogQuery(null, PathType.LogName, query); - logQuery.TolerateQueryErrors = true; - } - else - { - // - // There's only one key at this point, but we need an enumerator to get to it. - // - foreach (string log in _providersByLogMap.Keys) + + EventLogQuery logQuery = null; + if (_providersByLogMap.Count > 1) { - logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.LogName, query); + logQuery.TolerateQueryErrors = true; } - } - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; ; + else + { + // + // There's only one key at this point, but we need an enumerator to get to it. + // + foreach (string log in _providersByLogMap.Keys) + { + logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); + WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); + } + } + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; ; - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) - { - ReadEvents(readerObj); + ReadEvents(logQuery); } } @@ -597,66 +590,67 @@ private void ProcessGetProvider() // private void ProcessListLog() { - EventLogSession eventLogSession = CreateSession(); - - foreach (string logPattern in _listLog) + using (EventLogSession eventLogSession = CreateSession()) { - bool bMatchFound = false; - - foreach (string logName in eventLogSession.GetLogNames()) + foreach (string logPattern in _listLog) { - WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase); + bool bMatchFound = false; - if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) - && string.Equals(logPattern, logName, StringComparison.CurrentCultureIgnoreCase)) - || - (wildLogPattern.IsMatch(logName))) + foreach (string logName in eventLogSession.GetLogNames()) { - try - { - EventLogConfiguration logObj = new EventLogConfiguration(logName, eventLogSession); + WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase); - // - // Skip direct channels matching the wildcard unless -Force is present. - // - if (!Force.IsPresent && - WildcardPattern.ContainsWildcardCharacters(logPattern) && - (logObj.LogType == EventLogType.Debug || - logObj.LogType == EventLogType.Analytical)) + if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) + && string.Equals(logPattern, logName, StringComparison.CurrentCultureIgnoreCase)) + || + (wildLogPattern.IsMatch(logName))) + { + try { - continue; - } + EventLogConfiguration logObj = new EventLogConfiguration(logName, eventLogSession); + + // + // Skip direct channels matching the wildcard unless -Force is present. + // + if (!Force.IsPresent && + WildcardPattern.ContainsWildcardCharacters(logPattern) && + (logObj.LogType == EventLogType.Debug || + logObj.LogType == EventLogType.Analytical)) + { + continue; + } - EventLogInformation logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); + EventLogInformation logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); - PSObject outputObj = new PSObject(logObj); + PSObject outputObj = new PSObject(logObj); - outputObj.Properties.Add(new PSNoteProperty("FileSize", logInfoObj.FileSize)); - outputObj.Properties.Add(new PSNoteProperty("IsLogFull", logInfoObj.IsLogFull)); - outputObj.Properties.Add(new PSNoteProperty("LastAccessTime", logInfoObj.LastAccessTime)); - outputObj.Properties.Add(new PSNoteProperty("LastWriteTime", logInfoObj.LastWriteTime)); - outputObj.Properties.Add(new PSNoteProperty("OldestRecordNumber", logInfoObj.OldestRecordNumber)); - outputObj.Properties.Add(new PSNoteProperty("RecordCount", logInfoObj.RecordCount)); + outputObj.Properties.Add(new PSNoteProperty("FileSize", logInfoObj.FileSize)); + outputObj.Properties.Add(new PSNoteProperty("IsLogFull", logInfoObj.IsLogFull)); + outputObj.Properties.Add(new PSNoteProperty("LastAccessTime", logInfoObj.LastAccessTime)); + outputObj.Properties.Add(new PSNoteProperty("LastWriteTime", logInfoObj.LastWriteTime)); + outputObj.Properties.Add(new PSNoteProperty("OldestRecordNumber", logInfoObj.OldestRecordNumber)); + outputObj.Properties.Add(new PSNoteProperty("RecordCount", logInfoObj.RecordCount)); - WriteObject(outputObj); - bMatchFound = true; - } - catch (Exception exc) - { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("LogInfoUnavailable"), - logName, exc.Message); - Exception outerExc = new Exception(msg, exc); - WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); - continue; + WriteObject(outputObj); + bMatchFound = true; + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + logName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } } } - } - if (!bMatchFound) - { - string msg = _resourceMgr.GetString("NoMatchingLogsFound"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logPattern)); - WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, null)); + if (!bMatchFound) + { + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, null)); + } } } } @@ -666,45 +660,46 @@ private void ProcessListLog() // private void ProcessListProvider() { - EventLogSession eventLogSession = CreateSession(); - - foreach (string provPattern in _listProvider) + using (EventLogSession eventLogSession = CreateSession()) { - bool bMatchFound = false; - - foreach (string provName in eventLogSession.GetProviderNames()) + foreach (string provPattern in _listProvider) { - WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase); + bool bMatchFound = false; - if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) - && string.Equals(provPattern, provName, StringComparison.CurrentCultureIgnoreCase)) - || - (wildProvPattern.IsMatch(provName))) + foreach (string provName in eventLogSession.GetProviderNames()) { - try - { - ProviderMetadata provObj = new ProviderMetadata(provName, eventLogSession, CultureInfo.CurrentCulture); - WriteObject(provObj); - bMatchFound = true; - } - catch (System.Diagnostics.Eventing.Reader.EventLogException exc) + WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase); + + if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) + && string.Equals(provPattern, provName, StringComparison.CurrentCultureIgnoreCase)) + || + (wildProvPattern.IsMatch(provName))) { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("ProviderMetadataUnavailable"), - provName, exc.Message); - Exception outerExc = new Exception(msg, exc); - WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); - continue; + try + { + ProviderMetadata provObj = new ProviderMetadata(provName, eventLogSession, CultureInfo.CurrentCulture); + WriteObject(provObj); + bMatchFound = true; + } + catch (System.Diagnostics.Eventing.Reader.EventLogException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("ProviderMetadataUnavailable"), + provName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } } } - } - if (!bMatchFound) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoMatchingProvidersFound"), - _computerName, provPattern); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, null)); + if (!bMatchFound) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoMatchingProvidersFound"), + _computerName, provPattern); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, null)); + } } } } @@ -714,43 +709,40 @@ private void ProcessListProvider() // private void ProcessFilterXml() { - EventLogSession eventLogSession = CreateSession(); - - if (!Oldest.IsPresent) + using (EventLogSession eventLogSession = CreateSession()) { - // - // Do minimal parsing of xmlQuery to determine if any direct channels or ETL files are in it. - // - XmlElement root = _xmlQuery.DocumentElement; - XmlNodeList queryNodes = root.SelectNodes("//Query//Select"); - foreach (XmlNode queryNode in queryNodes) + if (!Oldest.IsPresent) { - XmlAttributeCollection attribs = queryNode.Attributes; - foreach (XmlAttribute attrib in attribs) + // + // Do minimal parsing of xmlQuery to determine if any direct channels or ETL files are in it. + // + XmlElement root = _xmlQuery.DocumentElement; + XmlNodeList queryNodes = root.SelectNodes("//Query//Select"); + foreach (XmlNode queryNode in queryNodes) { - if (attrib.Name.Equals("Path", StringComparison.OrdinalIgnoreCase)) + XmlAttributeCollection attribs = queryNode.Attributes; + foreach (XmlAttribute attrib in attribs) { - string logName = attrib.Value; - - if (logName.StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase)) + if (attrib.Name.Equals("Path", StringComparison.OrdinalIgnoreCase)) { - TerminateForNonEvtxFileWithoutOldest(logName); - } + string logName = attrib.Value; + + if (logName.StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase)) + { + TerminateForNonEvtxFileWithoutOldest(logName); + } - ValidateLogName(logName, eventLogSession); + ValidateLogName(logName, eventLogSession); + } } } } - } - EventLogQuery logQuery = new EventLogQuery(null, PathType.LogName, _xmlQuery.InnerXml); - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; + EventLogQuery logQuery = new EventLogQuery(null, PathType.LogName, _xmlQuery.InnerXml); + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) - { - ReadEvents(readerObj); + ReadEvents(logQuery); } } @@ -760,44 +752,41 @@ private void ProcessFilterXml() // private void ProcessFile() { - EventLogSession eventLogSession = CreateSession(); - - // - // At this point, _path array contains paths that might have wildcards, - // environment variables or PS drives. Let's resolve those. - // - for (int i = 0; i < _path.Length; i++) + using (EventLogSession eventLogSession = CreateSession()) { - StringCollection resolvedPaths = ValidateAndResolveFilePath(_path[i]); - foreach (string resolvedPath in resolvedPaths) + // + // At this point, _path array contains paths that might have wildcards, + // environment variables or PS drives. Let's resolve those. + // + for (int i = 0; i < _path.Length; i++) { - _resolvedPaths.Add(resolvedPath); - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath)); + StringCollection resolvedPaths = ValidateAndResolveFilePath(_path[i]); + foreach (string resolvedPath in resolvedPaths) + { + _resolvedPaths.Add(resolvedPath); + WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath)); + } } - } - EventLogQuery logQuery = null; - if (_resolvedPaths.Count == 0) - { - return; - } - else if (_resolvedPaths.Count > 1) - { - string query = BuildStructuredQuery(eventLogSession); - logQuery = new EventLogQuery(null, PathType.FilePath, query); - logQuery.TolerateQueryErrors = true; - } - else - { - logQuery = new EventLogQuery(_resolvedPaths[0], PathType.FilePath, _filter); - } - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; + EventLogQuery logQuery = null; + if (_resolvedPaths.Count == 0) + { + return; + } + else if (_resolvedPaths.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.FilePath, query); + logQuery.TolerateQueryErrors = true; + } + else + { + logQuery = new EventLogQuery(_resolvedPaths[0], PathType.FilePath, _filter); + } + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) - { - ReadEvents(readerObj); + ReadEvents(logQuery); } } @@ -808,23 +797,21 @@ private void ProcessHashQuery() { CheckHashTablesForNullValues(); - EventLogSession eventLogSession = CreateSession(); - - string query = BuildStructuredQuery(eventLogSession); - if (query.Length == 0) + using (EventLogSession eventLogSession = CreateSession()) { - return; - } - EventLogQuery logQuery = new EventLogQuery(null, PathType.FilePath, query); - logQuery.Session = eventLogSession; - logQuery.TolerateQueryErrors = true; - logQuery.ReverseDirection = !_oldest; + string query = BuildStructuredQuery(eventLogSession); + if (query.Length == 0) + { + return; + } - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) - { - ReadEvents(readerObj); + EventLogQuery logQuery = new EventLogQuery(null, PathType.FilePath, query); + logQuery.Session = eventLogSession; + logQuery.TolerateQueryErrors = true; + logQuery.ReverseDirection = !_oldest; + + ReadEvents(logQuery); } } @@ -874,57 +861,63 @@ private EventLogSession CreateSession() // // ReadEvents helper. // - private void ReadEvents(EventLogReader readerObj) + private void ReadEvents(EventLogQuery logQuery) { - Int64 numEvents = 0; - EventRecord evtObj = null; - - while (true) + using (EventLogReader readerObj = new EventLogReader(logQuery)) { - try + if (readerObj != null) { - evtObj = readerObj.ReadEvent(); - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); - continue; - } - if (evtObj == null) - { - break; - } - if (_maxEvents != -1 && numEvents >= _maxEvents) - { - break; - } + Int64 numEvents = 0; + EventRecord evtObj = null; + + while (true) + { + try + { + evtObj = readerObj.ReadEvent(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + continue; + } + if (evtObj == null) + { + break; + } + if (_maxEvents != -1 && numEvents >= _maxEvents) + { + break; + } - PSObject outputObj = new PSObject(evtObj); + PSObject outputObj = new PSObject(evtObj); - string evtMessage = _resourceMgr.GetString("NoEventMessage"); - try - { - evtMessage = evtObj.FormatDescription(); - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); - } - outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); + string evtMessage = _resourceMgr.GetString("NoEventMessage"); + try + { + evtMessage = evtObj.FormatDescription(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + } + outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); - // - // Enumerate the object one level to get to event payload - // - WriteObject(outputObj, true); - numEvents++; - } + // + // Enumerate the object one level to get to event payload + // + WriteObject(outputObj, true); + numEvents++; + } - if (numEvents == 0) - { - string msg = _resourceMgr.GetString("NoMatchingEventsFound"); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); + if (numEvents == 0) + { + string msg = _resourceMgr.GetString("NoMatchingEventsFound"); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); + } + } } } From 109063cd5e1452dd2063480514e4265c44dfb192 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Tue, 20 Jun 2017 09:17:55 +0300 Subject: [PATCH 2/2] Remove if (readerObj != null) --- .../GetEventCommand.cs | 87 +++++++++---------- 1 file changed, 42 insertions(+), 45 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index c3a68b81695..c44e17d1772 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -865,58 +865,55 @@ private void ReadEvents(EventLogQuery logQuery) { using (EventLogReader readerObj = new EventLogReader(logQuery)) { - if (readerObj != null) - { - Int64 numEvents = 0; - EventRecord evtObj = null; + Int64 numEvents = 0; + EventRecord evtObj = null; - while (true) + while (true) + { + try { - try - { - evtObj = readerObj.ReadEvent(); - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); - continue; - } - if (evtObj == null) - { - break; - } - if (_maxEvents != -1 && numEvents >= _maxEvents) - { - break; - } - - PSObject outputObj = new PSObject(evtObj); - - string evtMessage = _resourceMgr.GetString("NoEventMessage"); - try - { - evtMessage = evtObj.FormatDescription(); - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); - } - outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); + evtObj = readerObj.ReadEvent(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + continue; + } + if (evtObj == null) + { + break; + } + if (_maxEvents != -1 && numEvents >= _maxEvents) + { + break; + } + PSObject outputObj = new PSObject(evtObj); - // - // Enumerate the object one level to get to event payload - // - WriteObject(outputObj, true); - numEvents++; + string evtMessage = _resourceMgr.GetString("NoEventMessage"); + try + { + evtMessage = evtObj.FormatDescription(); } - - if (numEvents == 0) + catch (Exception exc) { - string msg = _resourceMgr.GetString("NoMatchingEventsFound"); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); } + outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); + + + // + // Enumerate the object one level to get to event payload + // + WriteObject(outputObj, true); + numEvents++; + } + + if (numEvents == 0) + { + string msg = _resourceMgr.GetString("NoMatchingEventsFound"); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); } } }