コード例 #1
0
 public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize)
 {
     this.session = session;
     this.logfile = logfile;
     this.cache = new Dictionary<ProviderMetadataId, CacheItem>();
     this.maximumCacheSize = maximumCacheSize;
 }
コード例 #2
0
 internal EventLogRecord(EventLogHandle handle, EventLogSession session, ProviderMetadataCachedInformation cachedMetadataInfo) {
     this.cachedMetadataInformation = cachedMetadataInfo;
     this.handle = handle;
     this.session = session;
     systemProperties = new NativeWrapper.SystemProperties();
     syncObject = new object();
 }
コード例 #3
0
        public EventLogConfiguration(string logName, EventLogSession session)
        {
            if (session == null)
                session = EventLogSession.GlobalSession;

            _session = session;
            _channelName = logName;

            _handle = NativeWrapper.EvtOpenChannelConfig(_session.Handle, _channelName, 0);
        }
 public EventLogConfiguration(string logName, EventLogSession session)
 {
     this.handle = EventLogHandle.Zero;
     EventLogPermissionHolder.GetEventLogPermission().Demand();
     if (session == null)
     {
         session = EventLogSession.GlobalSession;
     }
     this.session = session;
     this.channelName = logName;
     this.handle = NativeWrapper.EvtOpenChannelConfig(this.session.Handle, this.channelName, 0);
 }
コード例 #5
0
        public EventLogQuery(string path, PathType pathType, string query) {

            this.session = EventLogSession.GlobalSession;
            this.path = path;   // can be null
            this.pathType = pathType;

            if (query == null) {
                if (path == null)
                    throw new ArgumentNullException("path");
            }
            else {
                this.query = query;
            }
        }
コード例 #6
0
        internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath)
        {
            targetCultureInfo ??= CultureInfo.CurrentCulture;
            session ??= EventLogSession.GlobalSession;

            _session      = session;
            _providerName = providerName;
            _cultureInfo  = targetCultureInfo;
            _logFilePath  = logFilePath;

            _handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0);

            _syncObject = new object();
        }
コード例 #7
0
        internal EventLogInformation(EventLogSession session, string channelName, PathType pathType) {
            EventLogPermissionHolder.GetEventLogPermission().Demand();

            EventLogHandle logHandle = NativeWrapper.EvtOpenLog(session.Handle, channelName, pathType);

            using (logHandle) {
                creationTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime);
                lastAccessTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime);
                lastWriteTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime);
                fileSize = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize));
                fileAttributes = (int?)((uint?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes));
                recordCount = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords));
                oldestRecordNumber = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber));
                isLogFull = (bool?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull);
            }
        }
コード例 #8
0
ファイル: ProviderMetadata.cs プロジェクト: dfinke/powershell
        internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath)
        {
            if (targetCultureInfo == null)
                targetCultureInfo = CultureInfo.CurrentCulture;

            if (session == null)
                session = EventLogSession.GlobalSession;

            _session = session;
            _providerName = providerName;
            _cultureInfo = targetCultureInfo;
            _logFilePath = logFilePath;

            _handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0);

            _syncObject = new object();
        }
コード例 #9
0
        internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath) {

            EventLogPermissionHolder.GetEventLogPermission().Demand();

            if (targetCultureInfo == null)
                targetCultureInfo = CultureInfo.CurrentCulture;

            if (session == null)
                session = EventLogSession.GlobalSession;

            this.session = session;
            this.providerName = providerName;
            this.cultureInfo = targetCultureInfo;
            this.logFilePath = logFilePath;

            handle = NativeWrapper.EvtOpenProviderMetadata(this.session.Handle, this.providerName, this.logFilePath, this.cultureInfo.LCID, 0);

            this.syncObject = new object();
        }
コード例 #10
0
ファイル: EventLogInformation.cs プロジェクト: nickchal/pash
 internal EventLogInformation(EventLogSession session, string channelName, PathType pathType)
 {
     EventLogPermissionHolder.GetEventLogPermission().Demand();
     EventLogHandle handle = NativeWrapper.EvtOpenLog(session.Handle, channelName, pathType);
     using (handle)
     {
         this.creationTime = (DateTime?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime);
         this.lastAccessTime = (DateTime?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime);
         this.lastWriteTime = (DateTime?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime);
         long? nullable = (long?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize);
         this.fileSize = nullable.HasValue ? new long?(nullable.GetValueOrDefault()) : null;
         int? nullable3 = (int?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes);
         this.fileAttributes = nullable3.HasValue ? new int?(nullable3.GetValueOrDefault()) : null;
         long? nullable5 = (long?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords);
         this.recordCount = nullable5.HasValue ? new long?(nullable5.GetValueOrDefault()) : null;
         long? nullable7 = (long?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber);
         this.oldestRecordNumber = nullable7.HasValue ? new long?(nullable7.GetValueOrDefault()) : null;
         this.isLogFull = (bool?) NativeWrapper.EvtGetLogInfo(handle, Microsoft.Win32.UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull);
     }
 }
コード例 #11
0
ファイル: GetWinEventCommand.cs プロジェクト: nickchal/pash
 private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, string providerName)
 {
     try
     {
         ProviderMetadata metadata = new ProviderMetadata(providerName, eventLogSession, CultureInfo.CurrentCulture);
         foreach (EventLogLink link in metadata.LogLinks)
         {
             if (!this._providersByLogMap.ContainsKey(link.LogName.ToLower(CultureInfo.InvariantCulture)))
             {
                 EventLogConfiguration configuration = new EventLogConfiguration(link.LogName, eventLogSession);
                 if ((configuration.LogType == EventLogType.Debug) || (configuration.LogType == EventLogType.Analytical))
                 {
                     if (!this.Force.IsPresent)
                     {
                         continue;
                     }
                     this.ValidateLogName(link.LogName, eventLogSession);
                 }
                 base.WriteVerbose(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("ProviderLogLink"), new object[] { providerName, link.LogName }));
                 StringCollection strings = new StringCollection();
                 strings.Add(providerName.ToLower(CultureInfo.InvariantCulture));
                 this._providersByLogMap.Add(link.LogName.ToLower(CultureInfo.InvariantCulture), strings);
             }
             else
             {
                 StringCollection strings2 = this._providersByLogMap[link.LogName.ToLower(CultureInfo.InvariantCulture)];
                 if (!strings2.Contains(providerName.ToLower(CultureInfo.InvariantCulture)))
                 {
                     base.WriteVerbose(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("ProviderLogLink"), new object[] { providerName, link.LogName }));
                     strings2.Add(providerName.ToLower(CultureInfo.InvariantCulture));
                 }
             }
         }
     }
     catch (EventLogException exception)
     {
         Exception exception2 = new Exception(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("ProviderMetadataUnavailable"), new object[] { providerName, exception.Message }), exception);
         base.WriteError(new ErrorRecord(exception2, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null));
     }
 }
コード例 #12
0
        private static EventLogQuery GetQuery(string remoteComputer, string domain, string username, string password, string path, string queryString)
        {
            EventLogSession session;

            if (remoteComputer == null)
            {
                session = new EventLogSession();
            }
            else if (domain == null || username == null)
            {
                session = new EventLogSession(remoteComputer);
            }
            else
            {
                using (SecureString pw = new SecureString())
                {
                    password.ToList().ForEach(c => pw.AppendChar(c));
                    session = new EventLogSession(remoteComputer, domain, username, pw, SessionAuthentication.Default);
                }
            }

            // Query the Application log on the remote computer.
            return new EventLogQuery(path, PathType.LogName, queryString) { Session = session };
        }
コード例 #13
0
ファイル: ProviderMetadata.cs プロジェクト: dfinke/powershell
 public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo)
     : this(providerName, session, targetCultureInfo, null)
 {
 }
コード例 #14
0
        public string[] GetAllLogNames()
        {
            System.Collections.Generic.IList<string> allLogs = new System.Collections.Generic.List<string>();
            using (EventLogSession logSession = new EventLogSession())
            {
                IEnumerable<string> logNames = logSession.GetLogNames();
                foreach (string logName in logNames)
                {
                    using (EventLogConfiguration logConfig = new EventLogConfiguration(logName))
                    {
                        if (logConfig.IsEnabled)
                        {
                            allLogs.Add(logName);
                        }
                    }
                }
            }

            return allLogs.Cast<string>().ToArray();
        }
コード例 #15
0
ファイル: GetWinEventCommand.cs プロジェクト: nickchal/pash
 private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSession, IEnumerable<string> providerPatterns)
 {
     this._providersByLogMap.Clear();
     foreach (string str in providerPatterns)
     {
         bool flag = false;
         foreach (string str2 in eventLogSession.GetProviderNames())
         {
             WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
             if ((!WildcardPattern.ContainsWildcardCharacters(str) && str.Equals(str2, StringComparison.CurrentCultureIgnoreCase)) || pattern.IsMatch(str2))
             {
                 base.WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", new object[] { str2 }));
                 this.AddLogsForProviderToInternalMap(eventLogSession, str2);
                 flag = true;
             }
         }
         if (!flag)
         {
             string format = this._resourceMgr.GetString("NoMatchingProvidersFound");
             Exception exception = new Exception(string.Format(CultureInfo.InvariantCulture, format, new object[] { this._computerName, str }));
             base.WriteError(new ErrorRecord(exception, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, str));
         }
     }
 }
 public EventLogConfiguration(string logName, EventLogSession session)
 {
 }
コード例 #17
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
        //
        // BuildStructuredQueryFromHashTable() helper.
        // Builds a structured query from the hashtable (Selector) argument.
        //
        private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession)
        {
            string result = "";

            result = queryListOpen;

            uint queryId = 0;

            foreach (Hashtable hash in _selector)
            {
                string xpathString = "";

                CheckHashTableForQueryPathPresence(hash);

                //
                // Local queriedLogsQueryMap will hold names of logs or files to be queried
                // mapped to the actual query strings being built up.
                //
                Dictionary<string, string> queriedLogsQueryMap = new Dictionary<string, string>();

                //
                // Process log, _path, or provider parameters first
                // to create initial partially-filled query templates.
                // Error out for direct channels unless -oldest is present.
                // 
                // Order is important! Process "providername" key after "logname" and "file".
                //            
                if (hash.ContainsKey(hashkey_logname_lc))
                {
                    List<string> logPatterns = new List<string>();
                    if (hash[hashkey_logname_lc] is Array)
                    {
                        foreach (Object elt in (Array)hash[hashkey_logname_lc])
                        {
                            logPatterns.Add(elt.ToString());
                        }
                    }
                    else
                    {
                        logPatterns.Add(hash[hashkey_logname_lc].ToString());
                    }

                    FindLogNamesMatchingWildcards(eventLogSession, logPatterns);

                    foreach (string logName in _logNamesMatchingWildcard)
                    {
                        queriedLogsQueryMap.Add(logName.ToLowerInvariant(),
                                                string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, logName));
                    }
                }
                if (hash.ContainsKey(hashkey_path_lc))
                {
                    if (hash[hashkey_path_lc] is Array)
                    {
                        foreach (Object elt in (Array)hash[hashkey_path_lc])
                        {
                            StringCollection resolvedPaths = ValidateAndResolveFilePath(elt.ToString());
                            foreach (string resolvedPath in resolvedPaths)
                            {
                                queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(),
                                                        string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath));
                            }
                        }
                    }
                    else
                    {
                        StringCollection resolvedPaths = ValidateAndResolveFilePath(hash[hashkey_path_lc].ToString());
                        foreach (string resolvedPath in resolvedPaths)
                        {
                            queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(),
                                                    string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath));
                        }
                    }
                }
                if (hash.ContainsKey(hashkey_providername_lc))
                {
                    List<string> provPatterns = new List<string>();
                    if (hash[hashkey_providername_lc] is Array)
                    {
                        foreach (Object elt in (Array)hash[hashkey_providername_lc])
                        {
                            provPatterns.Add(elt.ToString());
                        }
                    }
                    else
                    {
                        provPatterns.Add(hash[hashkey_providername_lc].ToString());
                    }

                    FindProvidersByLogForWildcardPatterns(eventLogSession, provPatterns);

                    //
                    // If "providername" key is used alone, we will construct a query across all of the providers' logs.
                    // Otherwise, we will use the provider names to add predicates to "logname" and "path" queries.
                    //
                    if (!hash.ContainsKey(hashkey_path_lc) && !hash.ContainsKey(hashkey_logname_lc))
                    {
                        foreach (string keyLogName in _providersByLogMap.Keys)
                        {
                            string providersPredicate = BuildProvidersPredicate(_providersByLogMap[keyLogName]);
                            string query = string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, keyLogName);
                            queriedLogsQueryMap.Add(keyLogName.ToLowerInvariant(),
                                                     query + "[" + providersPredicate);
                        }
                    }
                    else
                    {
                        List<string> keysList = new List<string>(queriedLogsQueryMap.Keys);
                        bool bRemovedIrrelevantLogs = false;
                        foreach (string queriedLog in keysList)
                        {
                            if (queriedLog.StartsWith(filePrefix, StringComparison.Ordinal))
                            {
                                queriedLogsQueryMap[queriedLog] += "[" + BuildAllProvidersPredicate();
                            }
                            else
                            {
                                if (_providersByLogMap.ContainsKey(queriedLog))
                                {
                                    string providersPredicate = BuildProvidersPredicate(_providersByLogMap[queriedLog]);
                                    queriedLogsQueryMap[queriedLog] += "[" + providersPredicate;
                                }
                                else
                                {
                                    WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("SpecifiedProvidersDontWriteToLog"), queriedLog));
                                    queriedLogsQueryMap.Remove(queriedLog);
                                    bRemovedIrrelevantLogs = true;
                                }
                            }
                        }
                        //
                        // Write an error if we have removed all the logs as irrelevant
                        //
                        if (bRemovedIrrelevantLogs && (queriedLogsQueryMap.Count == 0))
                        {
                            string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("LogsAndProvidersDontOverlap"));
                            Exception exc = new Exception(msg);
                            WriteError(new ErrorRecord(exc, "LogsAndProvidersDontOverlap", ErrorCategory.InvalidArgument, null));
                            continue;
                        }
                    }
                }

                //
                // If none of the logs/paths/providers were valid, queriedLogsQueryMap is empty.
                // Simply continue to the next hashtable since all the errors have been written already.
                //
                if (queriedLogsQueryMap.Count == 0)
                {
                    continue;
                }

                //
                // At this point queriedLogsQueryMap contains all the query openings: missing the actual XPaths
                // Let's build xpathString to attach to each query opening.
                //
                bool bDateTimeHandled = false;
                foreach (string key in hash.Keys)
                {
                    string added = "";

                    switch (key.ToLowerInvariant())
                    {
                        case hashkey_logname_lc:
                        case hashkey_path_lc:
                        case hashkey_providername_lc:
                            break;
                        case hashkey_id_lc:
                            added = HandleEventIdHashValue(hash[key]);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }
                            break;

                        case hashkey_level_lc:
                            added = HandleLevelHashValue(hash[key]);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }
                            break;

                        case hashkey_keywords_lc:
                            added = HandleKeywordHashValue(hash[key]);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }
                            break;

                        case hashkey_starttime_lc:
                            if (bDateTimeHandled)
                            {
                                break;
                            }
                            added = HandleStartTimeHashValue(hash[key], hash);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }

                            bDateTimeHandled = true;
                            break;

                        case hashkey_endtime_lc:
                            if (bDateTimeHandled)
                            {
                                break;
                            }

                            added = HandleEndTimeHashValue(hash[key], hash);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }

                            bDateTimeHandled = true;
                            break;

                        case hashkey_data_lc:
                            added = HandleDataHashValue(hash[key]);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }
                            break;

                        case hashkey_userid_lc:
                            added = HandleContextHashValue(hash[key]);
                            if (added.Length > 0)
                            {
                                ExtendPredicate(ref xpathString);
                                xpathString += added;
                            }
                            break;

                        default:
                            {
                                //
                                // None of the recognized values: this must be a named payload field
                                //
                                ExtendPredicate(ref xpathString);
                                xpathString += string.Format(CultureInfo.InvariantCulture,
                                                            "([EventData[Data[@Name='{0}']='{1}']] or [UserData/*/{0}='{1}'])",
                                                            key, hash[key]);
                            }
                            break;
                    }
                }

                //
                // Complete each query with the XPath.
                // Handle the case where the query opener already has provider predicate(s).
                // Add the queries from queriedLogsQueryMap into the resulting string.
                //        
                foreach (string query in queriedLogsQueryMap.Values)
                {
                    result += query;

                    if (query.EndsWith("*", StringComparison.OrdinalIgnoreCase))
                    {
                        //
                        // No provider predicate: just add the XPath string
                        //
                        if (xpathString.Length != 0)
                        {
                            result += propOpen + xpathString + propClose;
                        }
                    }
                    else
                    {
                        //
                        // Add xpathString to provider predicates.
                        //
                        if (xpathString.Length != 0)
                        {
                            result += " and " + xpathString;
                        }
                        result += propClose;
                    }

                    result += queryCloser;
                }
            } //end foreach hashtable  


            result += queryListClose;

            return result;
        }
コード例 #18
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
        //
        // BuildStructuredQuery() builds a structured query from cmdlet arguments.
        //
        private string BuildStructuredQuery(EventLogSession eventLogSession)
        {
            string result = "";

            switch (ParameterSetName)
            {
                case "ListLogSet":
                    break;

                case "ListProviderSet":
                    break;

                case "GetProviderSet":
                    {
                        result = queryListOpen;
                        uint queryId = 0;

                        foreach (string log in _providersByLogMap.Keys)
                        {
                            string providerFilter = AddProviderPredicatesToFilter(_providersByLogMap[log]);
                            string addedQuery;
                            addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, providerFilter });
                            result += addedQuery;
                        }
                        result += queryListClose;
                    }
                    break;

                case "GetLogSet":
                    {
                        result = queryListOpen;
                        uint queryId = 0;
                        foreach (string log in _logNamesMatchingWildcard)
                        {
                            string addedQuery;
                            addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, _filter });
                            result += addedQuery;
                        }
                        result += queryListClose;
                    }
                    break;

                case "FileSet":
                    {
                        result = queryListOpen;
                        uint queryId = 0;
                        foreach (string filePath in _resolvedPaths)
                        {
                            string properFilePath = filePrefix + filePath;
                            string addedQuery;
                            addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, properFilePath, _filter });
                            result += addedQuery;
                        }
                        result += queryListClose;
                    }
                    break;

                case "HashQuerySet":
                    result = BuildStructuredQueryFromHashTable(eventLogSession);
                    break;

                default:
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName));
                    break;
            }

            WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("QueryTrace"), result));

            return result;
        }
コード例 #19
0
ファイル: MainForm.cs プロジェクト: ryanries/EventLogClearer
 void thread2_DoWork(object sender, DoWorkEventArgs e)
 {
     foreach (string computer in thread2Computers)
     {
         if (applicationEventLogCheckBox.Checked)
         {
             var eventLog = new EventLogSession();
             try
             {
                 if (securePW.Length > 0)
                     eventLog = new EventLogSession(computer, Environment.UserDomainName, usernameTextBox.Text, securePW, SessionAuthentication.Negotiate);
                 else
                     eventLog = new EventLogSession(computer);
                 eventLog.ClearLog("Application");
                 eventLog.Dispose();
                 ((BackgroundWorker)sender).ReportProgress(0, "Application log cleared on " + computer + ".");
             }
             catch (Exception ex)
             {
                 ((BackgroundWorker)sender).ReportProgress(0, "Failed to clear Application log on " + computer + ": " + ex.Message);
             }
         }
         if (securityEventLogCheckBox.Checked)
         {
             var eventLog = new EventLogSession();
             try
             {
                 if (securePW.Length > 0)
                     eventLog = new EventLogSession(computer, Environment.UserDomainName, usernameTextBox.Text, securePW, SessionAuthentication.Negotiate);
                 else
                     eventLog = new EventLogSession(computer);
                 eventLog.ClearLog("Security");
                 eventLog.Dispose();
                 ((BackgroundWorker)sender).ReportProgress(0, "Security log cleared on " + computer + ".");
             }
             catch (Exception ex)
             {
                 ((BackgroundWorker)sender).ReportProgress(0, "Failed to clear Security log on " + computer + ": " + ex.Message);
             }
         }
         if (setupEventLogCheckBox.Checked)
         {
             var eventLog = new EventLogSession();
             try
             {
                 if (securePW.Length > 0)
                     eventLog = new EventLogSession(computer, Environment.UserDomainName, usernameTextBox.Text, securePW, SessionAuthentication.Negotiate);
                 else
                     eventLog = new EventLogSession(computer);
                 eventLog.ClearLog("Setup");
                 eventLog.Dispose();
                 ((BackgroundWorker)sender).ReportProgress(0, "Setup log cleared on " + computer + ".");
             }
             catch (Exception ex)
             {
                 ((BackgroundWorker)sender).ReportProgress(0, "Failed to clear Setup log on " + computer + ": " + ex.Message);
             }
         }
         if (systemEventLogCheckBox.Checked)
         {
             var eventLog = new EventLogSession();
             try
             {
                 if (securePW.Length > 0)
                     eventLog = new EventLogSession(computer, Environment.UserDomainName, usernameTextBox.Text, securePW, SessionAuthentication.Negotiate);
                 else
                     eventLog = new EventLogSession(computer);
                 eventLog.ClearLog("System");
                 eventLog.Dispose();
                 ((BackgroundWorker)sender).ReportProgress(0, "System log cleared on " + computer + ".");
             }
             catch (Exception ex)
             {
                 ((BackgroundWorker)sender).ReportProgress(0, "Failed to clear System log on " + computer + ": " + ex.Message);
             }
         }
         if (appsAndSvcsLogsCheckBox.Checked)
         {
             var eventLog = new EventLogSession();
             try
             {
                 if (securePW.Length > 0)
                     eventLog = new EventLogSession(computer, Environment.UserDomainName, usernameTextBox.Text, securePW, SessionAuthentication.Negotiate);
                 else
                     eventLog = new EventLogSession(computer);
                 foreach (string log in eventLog.GetLogNames())
                 {
                     if (!(log.ToLower() == "application" || log.ToLower() == "setup" || log.ToLower() == "system" || log.ToLower() == "security"))
                     {
                         eventLog.ClearLog(log);
                         ((BackgroundWorker)sender).ReportProgress(0, log + " log cleared on " + computer + ".");
                     }
                 }
                 eventLog.Dispose();
             }
             catch (Exception ex)
             {
                 ((BackgroundWorker)sender).ReportProgress(0, "Failed to clear misc. log on " + computer + ": " + ex.Message);
             }
         }
     }
     ((BackgroundWorker)sender).ReportProgress(0, "Thread 2 finished.");
 }
コード例 #20
0
 public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize)
 {
     Debug.Assert(session != null);
     _session = session;
     _logfile = logfile;
     _cache = new Dictionary<ProviderMetadataId, CacheItem>();
     _maximumCacheSize = maximumCacheSize;
 }
コード例 #21
0
ファイル: ActiveDirectory.cs プロジェクト: KameronHott/Work
        /// <summary>
        /// Queries the event log
        /// </summary>
        /// <returns></returns>
        public string QueryADLog()
        {
            string sResults = "";
            string queryString = "*[System/Level=2]";
            SecureString pw = GetPassword();

            EventLogSession session = new EventLogSession("ncudbats01", "NCUL", "khott", pw, SessionAuthentication.Default);
            pw.Dispose();

            EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
            query.Session = session;

            try
            {
                EventLogReader logReader = new EventLogReader(query);
                sResults = DisplayEventInformation(logReader);
            }
            catch (EventLogException e)
            {
                sResults = "Could not query the remote computer! " + e.Message;
            }
            return sResults;
        }
コード例 #22
0
 public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo)
 {
     throw new NotImplementedException();
 }
コード例 #23
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
 //
 // ValidateLogName writes an error if logName is not a valid log.
 // It also terminates for direct ETW channels unless -Oldest is specified.                
 //
 private bool ValidateLogName(string logName, EventLogSession eventLogSession)
 {
     EventLogConfiguration logObj;
     try
     {
         logObj = new EventLogConfiguration(logName, eventLogSession);
     }
     catch (EventLogNotFoundException)
     {
         string msg = _resourceMgr.GetString("NoMatchingLogsFound");
         Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logName));
         WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logName));
         return false;
     }
     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));
         return false;
     }
     if (!Oldest.IsPresent)
     {
         if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical)
         {
             string msg = _resourceMgr.GetString("SpecifyOldestForLog");
             Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, logName));
             ThrowTerminatingError(new ErrorRecord(exc, "SpecifyOldestForLog", ErrorCategory.InvalidArgument, logName));
         }
     }
     return true;
 }
コード例 #24
0
ファイル: NewWinEventCommand.cs プロジェクト: 40a/PowerShell
        private void LoadProvider()
        {
            if (string.IsNullOrEmpty(_providerName))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName");
            }

            using (EventLogSession session = new EventLogSession())
            {
                foreach (string providerName in session.GetProviderNames())
                {
                    if (string.Equals(providerName, _providerName, StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            _providerMetadata = new ProviderMetadata(providerName);
                        }
                        catch (EventLogException exc)
                        {
                            string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message);
                            throw new Exception(msg, exc);
                        }
                        break;
                    }
                }
            }

            if (_providerMetadata == null)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), _providerName);
                throw new ArgumentException(msg);
            }
        }
コード例 #25
0
ファイル: EventLog.cs プロジェクト: vokac/F2B
        public EventLogInput(InputElement input, SelectorElement selector, EventQueue equeue)
            : base(input, selector, equeue)
        {
            // Event log query with suppressed events logged by this service
            StringBuilder qstr = new StringBuilder();
            qstr.Append("<QueryList>");
            qstr.Append("<Query>");
            qstr.Append(selector.Query.Value);
            qstr.Append("<Suppress Path=\"Application\">*[System/Provider/@Name=\"F2B\"]</Suppress>");
            qstr.Append("</Query>");
            qstr.Append("</QueryList>");

            EventLogSession session = null;
            if (input.Server != string.Empty)
            {
                SecureString pw = new SecureString();
                Array.ForEach(input.Password.ToCharArray(), pw.AppendChar);
                session = new EventLogSession(input.Server, input.Domain,
                                              input.Username, pw,
                                              SessionAuthentication.Default);
                pw.Dispose();
            }

            EventLogQuery query = new EventLogQuery(null, PathType.LogName, qstr.ToString());
            if (session != null)
            {
                query.Session = session;
            }

            // create event watcher (must be enable later)
            watcher = new EventLogWatcher(query);
            watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(
                    (s, a) => EventRead(s, a));

            // event data parsers (e.g. XPath + regex to extract event data)
            // (it is important to preserve order - it is later used as array index)
            List<Tuple<string, EventDataElement>> tmp = new List<Tuple<string, EventDataElement>>();
            tmp.Add(new Tuple<string,EventDataElement>("address", selector.Address));
            tmp.Add(new Tuple<string,EventDataElement>("port", selector.Port));
            tmp.Add(new Tuple<string,EventDataElement>("username", selector.Username));
            tmp.Add(new Tuple<string,EventDataElement>("domain", selector.Domain));

            evtmap = new Dictionary<string, Tuple<int, int>>();
            evtregex = new List<Regex>();
            List<string> xPathRefs = new List<string>();

            for (int i = 0; i < tmp.Count; i++)
            {
                string evtdescr = tmp[i].Item1;
                EventDataElement evtdata = tmp[i].Item2;

                if (evtdata == null || string.IsNullOrEmpty(evtdata.XPath))
                {
                    if (evtdescr == "address")
                    {
                        throw new ArgumentException("No address in " + Name + " configuration");
                    }

                    evtmap[evtdescr] = new Tuple<int, int>(i, -1);

                    continue;
                }

                Regex regex = null;
                if (!string.IsNullOrWhiteSpace(evtdata.Value))
                {
                    string evtstr = evtdata.Value.Trim();
                    try
                    {
                        regex = new Regex(evtstr, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    }
                    catch (ArgumentException ex)
                    {
                        Log.Error("Invalid " + Name + " " + evtdescr + " regex: "
                            + evtstr + " (" + ex.Message + ")");
                        throw;
                    }
                }

                evtregex.Add(regex);
                if (xPathRefs.Contains(evtdata.XPath))
                {
                    int index = xPathRefs.IndexOf(evtdata.XPath);
                    evtmap[evtdescr] = new Tuple<int, int>(i, index);
                }
                else
                {
                    xPathRefs.Add(evtdata.XPath);
                    evtmap[evtdescr] = new Tuple<int, int>(i, xPathRefs.Count - 1);
                }
            }

            Debug.Assert(tmp.Count == evtmap.Count,
                "Invalid index map size (tmp[" + tmp.Count
                + "] != map[" + evtmap.Count + "]).");

            evtsel = new EventLogPropertySelector(xPathRefs);
        }
コード例 #26
0
			private IDataReader ExecureEventLogReader()
			{
				EventLogQuery eventLogQuery = new EventLogQuery(
					null,
					PathType.LogName,
					this._eventLogQuery.TrimmedOrEmpty()
				);

				EventLogSession session = new EventLogSession(this._eventLogConnection.MachineName);
				eventLogQuery.Session   = session;

				EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

				Dictionary<string, string> mappings = _mappings.Count > 0
					? new Dictionary<string, string>(_mappings)
					: new Dictionary<string, string>(DefaultMappings);

				DataTable dt = new DataTable();
				foreach (KeyValuePair<string, string> mapping in mappings)
				{
					dt.Columns.Add(mapping.Key, typeof(string));
				}

				EventRecord eventInstance = eventLogReader.ReadEvent();

				while (eventInstance != null)
				{
					XmlDocument    eventDoc  = RemoveXmlns(eventInstance.ToXml());
					XPathNavigator navigator = eventDoc.CreateNavigator();
					DataRow        row       = dt.NewRow();

					foreach (KeyValuePair<string, string> mapping in mappings)
					{
						string         column = mapping.Key;
						string         xpath  = mapping.Value;
						XPathNavigator node   = navigator.SelectSingleNode(xpath);

						row[column] = node == null || node.Value == null
							? string.Empty
							: node.Value;
					}

					dt.Rows.Add(row);
					eventInstance = eventLogReader.ReadEvent();
				}

				return dt.CreateDataReader();
			}
コード例 #27
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
        //
        // FindLogNamesMatchingWildcards helper.
        // Finds all logs whose names match wildcard patterns in the 'logPatterns' argument.   
        // For each non-matched pattern, a non-terminating error is written.
        // The results are added to _logNamesMatchingWildcard array.  
        //
        private void FindLogNamesMatchingWildcards(EventLogSession eventLogSession, IEnumerable<string> logPatterns)
        {
            if (_logNamesMatchingWildcard == null)
            {
                _logNamesMatchingWildcard = new StringCollection();
            }
            else
            {
                _logNamesMatchingWildcard.Clear();
            }

            foreach (string logPattern in logPatterns)
            {
                bool bMatched = false;
                foreach (string actualLogName in eventLogSession.GetLogNames())
                {
                    WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase);

                    if (((!WildcardPattern.ContainsWildcardCharacters(logPattern))
                        && (logPattern.Equals(actualLogName, StringComparison.CurrentCultureIgnoreCase)))
                        ||
                        (wildLogPattern.IsMatch(actualLogName)))
                    {
                        //
                        // Skip direct ETW channels matching wildcards unless -force is present.
                        // Error out for direct channels unless -oldest is present.
                        //
                        EventLogConfiguration logObj;
                        try
                        {
                            logObj = new EventLogConfiguration(actualLogName, eventLogSession);
                        }
                        catch (Exception exc)
                        {
                            string msg = string.Format(CultureInfo.InvariantCulture,
                                                     _resourceMgr.GetString("LogInfoUnavailable"),
                                                     actualLogName, exc.Message);
                            Exception outerExc = new Exception(msg, exc);
                            WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null));
                            continue;
                        }

                        if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical)
                        {
                            if (WildcardPattern.ContainsWildcardCharacters(logPattern) && !Force.IsPresent)
                            {
                                continue;
                            }

                            ValidateLogName(actualLogName, eventLogSession);
                        }

                        if (!_logNamesMatchingWildcard.Contains(actualLogName.ToLowerInvariant()))
                        {
                            _logNamesMatchingWildcard.Add(actualLogName.ToLowerInvariant());
                        }
                        bMatched = true;
                    }
                }
                if (!bMatched)
                {
                    string msg = _resourceMgr.GetString("NoMatchingLogsFound");
                    Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logPattern));
                    WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logPattern));
                }
            }
        }
コード例 #28
0
        void CollectEventLogs(string logFileCollectionPath = "")
        {
            var els = new EventLogSession();

            // this query gets the last 7 days of events
            string q = "<QueryList>" +
                            "<Query Id=\"0\" Path=\"Application\">" +
                                "<Select Path=\"Application\">*[System[TimeCreated[timediff(@SystemTime) &lt;= 604800000]]]</Select>" +
                            "</Query>" +
                        "</QueryList>";
            els.ExportLogAndMessages("Application", PathType.LogName, q, Path.Combine(logFileCollectionPath + "\\Application.evtx"), false, CultureInfo.CurrentCulture);

            // this query gets the last 7 days of events
            q = "<QueryList>" +
                            "<Query Id=\"0\" Path=\"System\">" +
                                "<Select Path=\"System\">*[System[TimeCreated[timediff(@SystemTime) &lt;= 604800000]]]</Select>" +
                            "</Query>" +
                        "</QueryList>";
            els.ExportLogAndMessages("System", PathType.LogName, q, Path.Combine(logFileCollectionPath + "\\System.evtx"), false, CultureInfo.CurrentCulture);
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: JimJinn/iTest
        public void QueryRemoteComputer()
        {
            string queryString = "*[System/Level=2]"; // XPATH Query
            SecureString pw = GetPassword();

            EventLogSession session = new EventLogSession(
                "RemoteComputerName",                               // Remote Computer
                "Domain",                                  // Domain
                "Username",                                // Username
                pw,
                SessionAuthentication.Default);

            pw.Dispose();

            // Query the Application log on the remote computer.
            EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
            query.Session = session;

            try
            {
                EventLogReader logReader = new EventLogReader(query);

                // Display event info
                DisplayEventAndLogInformation(logReader);
            }
            catch (EventLogException e)
            {
                Console.WriteLine("Could not query the remote computer! " + e.Message);
                return;
            }
        }
コード例 #30
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
        //
        // FindProvidersByLogForWildcardPatterns helper.
        // Finds all providers whose names match wildcard patterns in 'providerPatterns' argument.   
        // For each non-matched pattern, a non-terminating error is written.
        // The results are added to _providersByLogMap dictionary (keyed by log names to which these providers write).  
        //
        private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSession, IEnumerable<string> providerPatterns)
        {
            _providersByLogMap.Clear();

            foreach (string provPattern in providerPatterns)
            {
                bool bMatched = false;
                foreach (string provName in eventLogSession.GetProviderNames())
                {
                    WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase);

                    if (((!WildcardPattern.ContainsWildcardCharacters(provPattern))
                      && (provPattern.Equals(provName, StringComparison.CurrentCultureIgnoreCase)))
                      ||
                      (wildProvPattern.IsMatch(provName)))
                    {
                        WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", provName));
                        AddLogsForProviderToInternalMap(eventLogSession, provName);
                        bMatched = true;
                    }
                }
                if (!bMatched)
                {
                    string msg = _resourceMgr.GetString("NoMatchingProvidersFound");
                    Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, provPattern));
                    WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, provPattern));
                }
            }
        }
コード例 #31
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
        //
        // AddLogsForProviderToInternalMap helper.
        // Retrieves log names to which _providerName writes.
        // NOTE: there are many misconfigured providers in the system.
        // We therefore catch EventLogException exceptions and write them out as non-terminating errors.
        // The results are added to _providersByLogMap dictionary.  
        //
        private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, string providerName)
        {
            try
            {
                ProviderMetadata providerMetadata = new ProviderMetadata(providerName, eventLogSession, CultureInfo.CurrentCulture);

                System.Collections.IEnumerable logLinks = providerMetadata.LogLinks;

                foreach (EventLogLink logLink in logLinks)
                {
                    if (!_providersByLogMap.ContainsKey(logLink.LogName.ToLowerInvariant()))
                    {
                        //
                        // Skip direct ETW channels unless -force is present.
                        // Error out for direct channels unless -oldest is present.
                        //                
                        EventLogConfiguration logObj = new EventLogConfiguration(logLink.LogName, eventLogSession);
                        if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical)
                        {
                            if (!Force.IsPresent)
                            {
                                continue;
                            }

                            ValidateLogName(logLink.LogName, eventLogSession);
                        }

                        WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName));

                        StringCollection provColl = new StringCollection();
                        provColl.Add(providerName.ToLowerInvariant());

                        _providersByLogMap.Add(logLink.LogName.ToLowerInvariant(), provColl);
                    }
                    else

                    {
                        //
                        // Log is there: add provider, if needed
                        //
                        StringCollection coll = _providersByLogMap[logLink.LogName.ToLowerInvariant()];

                        if (!coll.Contains(providerName.ToLowerInvariant()))
                        {
                            WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName));

                            coll.Add(providerName.ToLowerInvariant());
                        }
                    }
                }
            }
            catch (System.Diagnostics.Eventing.Reader.EventLogException exc)
            {
                string msg = string.Format(CultureInfo.InvariantCulture,
                                           _resourceMgr.GetString("ProviderMetadataUnavailable"),
                                           providerName, exc.Message);
                Exception outerExc = new Exception(msg, exc);
                WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null));
                return;
            }
        }
コード例 #32
0
ファイル: GetEventCommand.cs プロジェクト: dfinke/powershell
        //
        // CreateSession creates an EventLogSession connected to a target machine or localhost.
        // If _credential argument is PSCredential.Empty, the session will be created for the current context.
        //
        private EventLogSession CreateSession()
        {
            EventLogSession eventLogSession = null;

            if (_computerName == string.Empty)
            {
                // Set _computerName to "localhost" for future error messages,
                // but do not use it for the connection to avoid RPC overhead.            
                _computerName = "localhost";

                if (_credential == PSCredential.Empty)
                {
                    return new EventLogSession();
                }
            }
            else if (_credential == PSCredential.Empty)
            {
                return new EventLogSession(_computerName);
            }

            // If we are here, either both computer name and credential were passed initially,
            // or credential only - we will use it with "localhost"

            NetworkCredential netCred = (NetworkCredential)_credential;
            eventLogSession = new EventLogSession(_computerName,
                                 netCred.Domain,
                                 netCred.UserName,
                                 _credential.Password,
                                 SessionAuthentication.Default
                                 );
            //
            // Force the destruction of cached password
            //
            netCred.Password = "";

            return eventLogSession;
        }