MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System;5using System.Collections;6using System.Collections.Generic;7using System.ComponentModel; // Win32Exception8using System.Diagnostics; // Eventlog class9using System.Diagnostics.CodeAnalysis;10using System.Management.Automation;11using System.Management.Automation.Internal;12 13namespace Microsoft.PowerShell.Commands14{15 #region GetEventLogCommand16 /// <summary>17 /// This class implements the Get-EventLog command.18 /// </summary>19 /// <remarks>20 /// The CLR EventLogEntryCollection class has problems with managing21 /// rapidly spinning logs (i.e. logs set to "Overwrite" which are22 /// rapidly getting new events and discarding old events).23 /// In particular, if you enumerate forward24 /// EventLogEntryCollection entries = log.Entries;25 /// foreach (EventLogEntry entry in entries)26 /// it will occasionally skip an entry. Conversely, if you are27 /// enumerating backward28 /// EventLogEntryCollection entries = log.Entries;29 /// int count = entries.Count;30 /// for (int i = count-1; i >= 0; i--) {31 /// EventLogEntry entry = entries[i];32 /// it will occasionally repeat an entry. Accordingly, we enumerate33 /// backward and try to leave off the repeated entries.34 /// </remarks>35 [Cmdlet(VerbsCommon.Get, "EventLog", DefaultParameterSetName = "LogName",36 HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113314", RemotingCapability = RemotingCapability.SupportedByCommand)]37 [OutputType(typeof(EventLog), typeof(EventLogEntry), typeof(string))]38 public sealed class GetEventLogCommand : PSCmdlet39 {40 #region Parameters41 /// <summary>42 /// Read eventlog entries from this log.43 /// </summary>44 [Parameter(Position = 0, Mandatory = true, ParameterSetName = "LogName")]45 [Alias("LN")]46 public string LogName { get; set; }47 48 /// <summary>49 /// Read eventlog entries from this computer.50 /// </summary>51 [Parameter]52 [ValidateNotNullOrEmpty]53 [Alias("Cn")]54 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]55 public string[] ComputerName { get; set; } = Array.Empty<string>();56 57 /// <summary>58 /// Read only this number of entries.59 /// </summary>60 [Parameter(ParameterSetName = "LogName")]61 [ValidateRange(0, Int32.MaxValue)]62 public int Newest { get; set; } = Int32.MaxValue;63 64 /// <summary>65 /// Return entries "after " this date.66 /// </summary>67 [Parameter(ParameterSetName = "LogName")]68 [ValidateNotNullOrEmpty]69 public DateTime After70 {71 get { return _after; }72 73 set74 {75 _after = value;76 _isDateSpecified = true;77 _isFilterSpecified = true;78 }79 }80 81 private DateTime _after;82 83 /// <summary>84 /// Return entries "Before" this date.85 /// </summary>86 [Parameter(ParameterSetName = "LogName")]87 [ValidateNotNullOrEmpty]88 public DateTime Before89 {90 get { return _before; }91 92 set93 {94 _before = value;95 _isDateSpecified = true;96 _isFilterSpecified = true;97 }98 }99 100 private DateTime _before;101 102 /// <summary>103 /// Return entries for this user.Wild characters is supported.104 /// </summary>105 [Parameter(ParameterSetName = "LogName")]106 [ValidateNotNullOrEmpty]107 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]108 public string[] UserName109 {110 get { return _username; }111 112 set113 {114 _username = value;115 _isFilterSpecified = true;116 }117 }118 119 private string[] _username;120 121 /// <summary>122 /// Match eventlog entries by the InstanceIds123 /// gets or sets an array of instanceIds.124 /// </summary>125 [Parameter(Position = 1, ParameterSetName = "LogName")]126 [ValidateNotNullOrEmpty]127 [ValidateRangeAttribute((long)0, long.MaxValue)]128 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]129 public long[] InstanceId130 {131 get { return _instanceIds; }132 133 set134 {135 _instanceIds = value;136 _isFilterSpecified = true;137 }138 }139 140 private long[] _instanceIds = null;141 142 /// <summary>143 /// Match eventlog entries by the Index144 /// gets or sets an array of indexes.145 /// </summary>146 [Parameter(ParameterSetName = "LogName")]147 [ValidateNotNullOrEmpty]148 [ValidateRangeAttribute((int)1, int.MaxValue)]149 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]150 public int[] Index151 {152 get { return _indexes; }153 154 set155 {156 _indexes = value;157 _isFilterSpecified = true;158 }159 }160 161 private int[] _indexes = null;162 163 /// <summary>164 /// Match eventlog entries by the EntryType165 /// gets or sets an array of EntryTypes.166 /// </summary>167 [Parameter(ParameterSetName = "LogName")]168 [ValidateNotNullOrEmpty]169 [ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })]170 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]171 [Alias("ET")]172 public string[] EntryType173 {174 get { return _entryTypes; }175 176 set177 {178 _entryTypes = value;179 _isFilterSpecified = true;180 }181 }182 183 private string[] _entryTypes = null;184 185 /// <summary>186 /// Get or sets an array of Source.187 /// </summary>188 [Parameter(ParameterSetName = "LogName")]189 [ValidateNotNullOrEmpty]190 [Alias("ABO")]191 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]192 public string[] Source193 {194 get195 { return _sources; }196 197 set198 {199 _sources = value;200 _isFilterSpecified = true;201 }202 }203 204 private string[] _sources;205 206 /// <summary>207 /// Get or Set Message string to searched in EventLog.208 /// </summary>209 [Parameter(ParameterSetName = "LogName")]210 [ValidateNotNullOrEmpty]211 [Alias("MSG")]212 public string Message213 {214 get215 {216 return _message;217 }218 219 set220 {221 _message = value;222 _isFilterSpecified = true;223 }224 }225 226 private string _message;227 228 /// <summary>229 /// Returns Log Entry as base object.230 /// </summary>231 [Parameter(ParameterSetName = "LogName")]232 public SwitchParameter AsBaseObject { get; set; }233 234 /// <summary>235 /// Return the Eventlog objects rather than the log contents.236 /// </summary>237 [Parameter(ParameterSetName = "List")]238 public SwitchParameter List { get; set; }239 240 /// <summary>241 /// Return the log names rather than the EventLog objects.242 /// </summary>243 [Parameter(ParameterSetName = "List")]244 public SwitchParameter AsString245 {246 get247 {248 return _asString;249 }250 251 set252 {253 _asString = value;254 }255 }256 257 private bool _asString /* = false */;258 #endregion Parameters259 260 #region Overrides261 262 /// <summary>263 /// Sets true when Filter is Specified.264 /// </summary>265 private bool _isFilterSpecified = false;266 private bool _isDateSpecified = false;267 private bool _isThrowError = true;268 269 /// <summary>270 /// Process the specified logs.271 /// </summary>272 protected override void BeginProcessing()273 {274 if (ParameterSetName == "List")275 {276 if (ComputerName.Length > 0)277 {278 foreach (string computerName in ComputerName)279 {280 foreach (EventLog log in EventLog.GetEventLogs(computerName))281 {282 if (AsString)283 WriteObject(log.Log);284 else285 WriteObject(log);286 }287 }288 }289 else290 {291 foreach (EventLog log in EventLog.GetEventLogs())292 {293 if (AsString)294 WriteObject(log.Log);295 else296 WriteObject(log);297 }298 }299 }300 else301 {302 Diagnostics.Assert(ParameterSetName == "LogName", "Unexpected parameter set");303 304 if (!WildcardPattern.ContainsWildcardCharacters(LogName))305 {306 OutputEvents(LogName);307 }308 else309 {310 //311 // If we were given a wildcard that matches more than one log, output the matching logs. Otherwise output the events in the matching log.312 //313 List<EventLog> matchingLogs = GetMatchingLogs(LogName);314 315 if (matchingLogs.Count == 1)316 {317 OutputEvents(matchingLogs[0].Log);318 }319 else320 {321 foreach (EventLog log in matchingLogs)322 {323 WriteObject(log);324 }325 }326 }327 }328 }329 #endregion Overrides330 331 #region Private332 333 private void OutputEvents(string logName)334 {335 // 2005/04/21-JonN This somewhat odd structure works336 // around the FXCOP DisposeObjectsBeforeLosingScope rule.337 bool processing = false;338 try339 {340 if (ComputerName.Length == 0)341 {342 using (EventLog specificLog = new EventLog(logName))343 {344 processing = true;345 Process(specificLog);346 }347 }348 else349 {350 processing = true;351 352 foreach (string computerName in ComputerName)353 {354 using (EventLog specificLog = new EventLog(logName, computerName))355 {356 Process(specificLog);357 }358 }359 }360 }361 catch (InvalidOperationException e)362 {363 if (processing)364 {365 throw;366 }367 368 ThrowTerminatingError(new ErrorRecord(369 e, // default exception text is OK370 "EventLogNotFound",371 ErrorCategory.ObjectNotFound,372 logName));373 }374 }375 376 private void Process(EventLog log)377 {378 bool matchesfound = false;379 if (Newest == 0)380 {381 return;382 }383 384 // enumerate backward, skipping repeat entries385 EventLogEntryCollection entries = log.Entries;386 387 int count = entries.Count;388 int lastindex = Int32.MinValue;389 int processed = 0;390 391 for (int i = count - 1; (i >= 0) && (processed < Newest); i--)392 {393 EventLogEntry entry = null;394 try395 {396 entry = entries[i];397 }398 catch (ArgumentException e)399 {400 ErrorRecord er = new ErrorRecord(401 e,402 "LogReadError",403 ErrorCategory.ReadError,404 null405 );406 er.ErrorDetails = new ErrorDetails(407 this,408 "EventlogResources",409 "LogReadError",410 log.Log,411 e.Message412 );413 WriteError(er);414 415 // NTRAID#Windows Out Of Band Releases-2005/09/27-JonN416 // Break after the first one, rather than repeating this417 // over and over418 break;419 }420 catch (Exception e)421 {422 Diagnostics.Assert(false,423 "EventLogEntryCollection error "424 + e.GetType().FullName425 + ": " + e.Message);426 throw;427 }428 429 if ((entry != null) &&430 ((lastindex == Int32.MinValue431 || lastindex - entry.Index == 1)))432 {433 lastindex = entry.Index;434 if (_isFilterSpecified)435 {436 if (!FiltersMatch(entry))437 continue;438 }439 440 if (!AsBaseObject)441 {442 // wrapping in PSobject to insert into PStypesnames443 PSObject logentry = new PSObject(entry);444 // inserting at zero position in reverse order445 logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source);446 logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source + "/" + entry.InstanceId);447 WriteObject(logentry);448 matchesfound = true;449 }450 else451 {452 WriteObject(entry);453 matchesfound = true;454 }455 456 processed++;457 }458 }459 460 if (!matchesfound && _isThrowError)461 {462 Exception Ex = new ArgumentException(StringUtil.Format(EventlogResources.NoEntriesFound, log.Log, string.Empty));463 WriteError(new ErrorRecord(Ex, "GetEventLogNoEntriesFound", ErrorCategory.ObjectNotFound, null));464 }465 }466 467 private bool FiltersMatch(EventLogEntry entry)468 {469 if (_indexes != null)470 {471 if (!((IList)_indexes).Contains(entry.Index))472 {473 return false;474 }475 }476 477 if (_instanceIds != null)478 {479 if (!((IList)_instanceIds).Contains(entry.InstanceId))480 {481 return false;482 }483 }484 485 if (_entryTypes != null)486 {487 bool entrymatch = false;488 foreach (string type in _entryTypes)489 {490 if (type.Equals(entry.EntryType.ToString(), StringComparison.OrdinalIgnoreCase))491 {492 entrymatch = true;493 break;494 }495 }496 497 if (!entrymatch)498 {499 return entrymatch;500 }501 }502 503 if (_sources != null)504 {505 bool sourcematch = false;506 foreach (string source in _sources)507 {508 if (WildcardPattern.ContainsWildcardCharacters(source))509 {510 _isThrowError = false;511 }512 513 WildcardPattern wildcardpattern = WildcardPattern.Get(source, WildcardOptions.IgnoreCase);514 if (wildcardpattern.IsMatch(entry.Source))515 {516 sourcematch = true;517 break;518 }519 }520 521 if (!sourcematch)522 {523 return sourcematch;524 }525 }526 527 if (_message != null)528 {529 if (WildcardPattern.ContainsWildcardCharacters(_message))530 {531 _isThrowError = false;532 }533 534 WildcardPattern wildcardpattern = WildcardPattern.Get(_message, WildcardOptions.IgnoreCase);535 if (!wildcardpattern.IsMatch(entry.Message))536 {537 return false;538 }539 }540 541 if (_username != null)542 {543 bool usernamematch = false;544 foreach (string user in _username)545 {546 _isThrowError = false;547 if (entry.UserName != null)548 {549 WildcardPattern wildcardpattern = WildcardPattern.Get(user, WildcardOptions.IgnoreCase);550 if (wildcardpattern.IsMatch(entry.UserName))551 {552 usernamematch = true;553 break;554 }555 }556 }557 558 if (!usernamematch)559 {560 return usernamematch;561 }562 }563 564 if (_isDateSpecified)565 {566 _isThrowError = false;567 bool datematch = false;568 if (!_after.Equals(_initial) && _before.Equals(_initial))569 {570 if (entry.TimeGenerated > _after)571 {572 datematch = true;573 }574 }575 else if (!_before.Equals(_initial) && _after.Equals(_initial))576 {577 if (entry.TimeGenerated < _before)578 {579 datematch = true;580 }581 }582 else if (!_after.Equals(_initial) && !_before.Equals(_initial))583 {584 if (_after > _before || _after == _before)585 {586 if ((entry.TimeGenerated > _after) || (entry.TimeGenerated < _before))587 datematch = true;588 }589 else590 {591 if ((entry.TimeGenerated > _after) && (entry.TimeGenerated < _before))592 {593 datematch = true;594 }595 }596 }597 598 if (!datematch)599 {600 return datematch;601 }602 }603 604 return true;605 }606 607 private List<EventLog> GetMatchingLogs(string pattern)608 {609 WildcardPattern wildcardPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);610 List<EventLog> matchingLogs = new List<EventLog>();611 if (ComputerName.Length == 0)612 {613 foreach (EventLog log in EventLog.GetEventLogs())614 {615 if (wildcardPattern.IsMatch(log.Log))616 {617 matchingLogs.Add(log);618 }619 }620 }621 else622 {623 foreach (string computerName in ComputerName)624 {625 foreach (EventLog log in EventLog.GetEventLogs(computerName))626 {627 if (wildcardPattern.IsMatch(log.Log))628 {629 matchingLogs.Add(log);630 }631 }632 }633 }634 635 return matchingLogs;636 }637 // private string ErrorBase = "EventlogResources";638 private DateTime _initial = new DateTime();639 640 #endregion Private641 }642 #endregion GetEventLogCommand643 644 #region ClearEventLogCommand645 /// <summary>646 /// This class implements the Clear-EventLog command.647 /// </summary>648 649 [Cmdlet(VerbsCommon.Clear, "EventLog", SupportsShouldProcess = true,650 HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135198", RemotingCapability = RemotingCapability.SupportedByCommand)]651 public sealed class ClearEventLogCommand : PSCmdlet652 {653 #region Parameters654 /// <summary>655 /// Clear these logs.656 /// </summary>657 [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)]658 [Alias("LN")]659 [ValidateNotNullOrEmpty]660 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]661 public string[] LogName { get; set; }662 663 /// <summary>664 /// Clear eventlog entries from these Computers.665 /// </summary>666 [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]667 [ValidateNotNullOrEmpty]668 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]669 [Alias("Cn")]670 public string[] ComputerName { get; set; } = { "." };671 672 #endregion Parameters673 674 #region Overrides675 676 /// <summary>677 /// Does the processing.678 /// </summary>679 protected override void BeginProcessing()680 {681 string computer = string.Empty;682 foreach (string compName in ComputerName)683 {684 if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase)))685 {686 computer = "localhost";687 }688 else689 {690 computer = compName;691 }692 693 foreach (string eventString in LogName)694 {695 try696 {697 if (!EventLog.Exists(eventString, compName))698 {699 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, eventString, computer)), null, ErrorCategory.InvalidOperation, null);700 WriteError(er);701 continue;702 }703 704 if (!ShouldProcess(StringUtil.Format(EventlogResources.ClearEventLogWarning, eventString, computer)))705 {706 continue;707 }708 709 EventLog Log = new EventLog(eventString, compName);710 Log.Clear();711 }712 catch (System.IO.IOException)713 {714 ErrorRecord er = new ErrorRecord(new System.IO.IOException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null);715 WriteError(er);716 continue;717 }718 catch (Win32Exception)719 {720 ErrorRecord er = new ErrorRecord(new Win32Exception(StringUtil.Format(EventlogResources.NoAccess, null, computer)), null, ErrorCategory.PermissionDenied, null);721 WriteError(er);722 continue;723 }724 catch (InvalidOperationException)725 {726 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.OSWritingError)), null, ErrorCategory.ReadError, null);727 WriteError(er);728 continue;729 }730 }731 }732 }733 734 // beginprocessing735 736 #endregion Overrides737 }738 #endregion ClearEventLogCommand739 740 #region WriteEventLogCommand741 /// <summary>742 /// This class implements the Write-EventLog command.743 /// </summary>744 745 [Cmdlet(VerbsCommunications.Write, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135281", RemotingCapability = RemotingCapability.SupportedByCommand)]746 public sealed class WriteEventLogCommand : PSCmdlet747 {748 #region Parameters749 /// <summary>750 /// Write eventlog entries in this log.751 /// </summary>752 [Parameter(Position = 0, Mandatory = true)]753 [Alias("LN")]754 [ValidateNotNullOrEmpty]755 public string LogName { get; set; }756 757 /// <summary>758 /// The source by which the application is registered on the specified computer.759 /// </summary>760 [Parameter(Position = 1, Mandatory = true)]761 [Alias("SRC")]762 [ValidateNotNullOrEmpty]763 public string Source { get; set; }764 765 /// <summary>766 /// String which represents One of the EventLogEntryType values.767 /// </summary>768 [Parameter(Position = 3)]769 [Alias("ET")]770 [ValidateNotNullOrEmpty]771 [ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })]772 public EventLogEntryType EntryType { get; set; } = EventLogEntryType.Information;773 774 /// <summary>775 /// The application-specific subcategory associated with the message.776 /// </summary>777 [Parameter]778 public Int16 Category { get; set; } = 1;779 780 /// <summary>781 /// The application-specific identifier for the event.782 /// </summary>783 [Parameter(Position = 2, Mandatory = true)]784 [Alias("ID", "EID")]785 [ValidateNotNullOrEmpty]786 [ValidateRange(0, UInt16.MaxValue)]787 public Int32 EventId { get; set; }788 789 /// <summary>790 /// The message goes here.791 /// </summary>792 [Parameter(Position = 4, Mandatory = true)]793 [Alias("MSG")]794 [ValidateNotNullOrEmpty]795 [ValidateLength(0, 32766)]796 public string Message { get; set; }797 798 /// <summary>799 /// Write eventlog entries of this log.800 /// </summary>801 [Parameter]802 [Alias("RD")]803 [ValidateNotNullOrEmpty]804 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]805 public byte[] RawData { get; set; }806 807 /// <summary>808 /// Write eventlog entries of this log.809 /// </summary>810 [Parameter]811 [Alias("CN")]812 [ValidateNotNullOrEmpty]813 814 public string ComputerName { get; set; } = ".";815 816 #endregion Parameters817 #region private818 819 private void WriteNonTerminatingError(Exception exception, string errorId, string errorMessage,820 ErrorCategory category)821 {822 Exception ex = new Exception(errorMessage, exception);823 WriteError(new ErrorRecord(ex, errorId, category, null));824 }825 826 #endregion private827 #region Overrides828 829 /// <summary>830 /// Does the processing.831 /// </summary>832 protected override void BeginProcessing()833 {834 string _computerName = string.Empty;835 if ((ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (ComputerName.Equals(".", StringComparison.OrdinalIgnoreCase)))836 {837 _computerName = "localhost";838 }839 else840 {841 _computerName = ComputerName;842 }843 844 try845 {846 if (!(EventLog.SourceExists(Source, ComputerName)))847 {848 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, null, _computerName, Source)), null, ErrorCategory.InvalidOperation, null);849 WriteError(er);850 }851 else852 {853 if (!(EventLog.Exists(LogName, ComputerName)))854 {855 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, LogName, _computerName)), null, ErrorCategory.InvalidOperation, null);856 WriteError(er);857 }858 else859 {860 EventLog _myevent = new EventLog(LogName, ComputerName, Source);861 _myevent.WriteEntry(Message, EntryType, EventId, Category, RawData);862 }863 }864 }865 catch (ArgumentException ex)866 {867 WriteNonTerminatingError(ex, ex.Message, ex.Message, ErrorCategory.InvalidOperation);868 }869 catch (InvalidOperationException ex)870 {871 WriteNonTerminatingError(ex, "AccessDenied", StringUtil.Format(EventlogResources.AccessDenied, LogName, null, Source), ErrorCategory.PermissionDenied);872 }873 catch (Win32Exception ex)874 {875 WriteNonTerminatingError(ex, "OSWritingError", StringUtil.Format(EventlogResources.OSWritingError, null, null, null), ErrorCategory.WriteError);876 }877 catch (System.IO.IOException ex)878 {879 WriteNonTerminatingError(ex, "PathDoesNotExist", StringUtil.Format(EventlogResources.PathDoesNotExist, null, ComputerName, null), ErrorCategory.InvalidOperation);880 }881 }882 883 #endregion Overrides884 }885 #endregion WriteEventLogCommand886 887 #region LimitEventLogCommand888 /// <summary>889 /// This class implements the Limit-EventLog command.890 /// </summary>891 892 [Cmdlet(VerbsData.Limit, "EventLog", SupportsShouldProcess = true,893 HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135227", RemotingCapability = RemotingCapability.SupportedByCommand)]894 public sealed class LimitEventLogCommand : PSCmdlet895 {896 #region Parameters897 /// <summary>898 /// Limit the properties of this log.899 /// </summary>900 [Parameter(Position = 0, Mandatory = true)]901 [Alias("LN")]902 [ValidateNotNullOrEmpty]903 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]904 public string[] LogName { get; set; }905 906 /// <summary>907 /// Limit eventlog entries of this computer.908 /// </summary>909 [Parameter]910 [Alias("CN")]911 [ValidateNotNullOrEmpty]912 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]913 public string[] ComputerName { get; set; } = { "." };914 915 /// <summary>916 /// Minimum retention days for this log.917 /// </summary>918 [Parameter]919 [Alias("MRD")]920 [ValidateNotNullOrEmpty]921 [ValidateRange(1, 365)]922 public Int32 RetentionDays923 {924 get { return _retention; }925 926 set927 {928 _retention = value;929 _retentionSpecified = true;930 }931 }932 933 private Int32 _retention;934 private bool _retentionSpecified = false;935 /// <summary>936 /// Overflow action to be taken.937 /// </summary>938 [Parameter]939 [Alias("OFA")]940 [ValidateNotNullOrEmpty]941 [ValidateSetAttribute(new string[] { "OverwriteOlder", "OverwriteAsNeeded", "DoNotOverwrite" })]942 943 public System.Diagnostics.OverflowAction OverflowAction944 {945 get { return _overflowaction; }946 947 set948 {949 _overflowaction = value;950 _overflowSpecified = true;951 }952 }953 954 private System.Diagnostics.OverflowAction _overflowaction;955 private bool _overflowSpecified = false;956 /// <summary>957 /// Maximum size of this log.958 /// </summary>959 [Parameter]960 [ValidateNotNullOrEmpty]961 public Int64 MaximumSize962 {963 get { return _maximumKilobytes; }964 965 set966 {967 _maximumKilobytes = value;968 _maxkbSpecified = true;969 }970 }971 972 private Int64 _maximumKilobytes;973 private bool _maxkbSpecified = false;974 #endregion Parameters975 976 #region private977 private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId,978 ErrorCategory category, string _logName, string _compName)979 {980 Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName), exception);981 WriteError(new ErrorRecord(ex, errorId, category, null));982 }983 984 #endregion private985 986 #region Overrides987 988 /// <summary>989 /// Does the processing.990 /// </summary>991 protected override992 void993 BeginProcessing()994 {995 string computer = string.Empty;996 foreach (string compname in ComputerName)997 {998 if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase)))999 {1000 computer = "localhost";1001 }1002 else1003 {1004 computer = compname;1005 }1006 1007 foreach (string logname in LogName)1008 {1009 try1010 {1011 if (!EventLog.Exists(logname, compname))1012 {1013 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, logname, computer)), null, ErrorCategory.InvalidOperation, null);1014 WriteError(er);1015 continue;1016 }1017 else1018 {1019 if (!ShouldProcess(StringUtil.Format(EventlogResources.LimitEventLogWarning, logname, computer)))1020 {1021 continue;1022 }1023 else1024 {1025 EventLog newLog = new EventLog(logname, compname);1026 int _minRetention = newLog.MinimumRetentionDays;1027 System.Diagnostics.OverflowAction _newFlowAction = newLog.OverflowAction;1028 if (_retentionSpecified && _overflowSpecified)1029 {1030 if (_overflowaction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0)1031 {1032 newLog.ModifyOverflowPolicy(_overflowaction, _retention);1033 }1034 else1035 {1036 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null);1037 WriteError(er);1038 continue;1039 }1040 }1041 else if (_retentionSpecified && !_overflowSpecified)1042 {1043 if (_newFlowAction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0)1044 {1045 newLog.ModifyOverflowPolicy(_newFlowAction, _retention);1046 }1047 else1048 {1049 ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null);1050 WriteError(er);1051 continue;1052 }1053 }1054 else if (!_retentionSpecified && _overflowSpecified)1055 {1056 newLog.ModifyOverflowPolicy(_overflowaction, _minRetention);1057 }1058 1059 if (_maxkbSpecified)1060 {1061 int kiloByte = 1024;1062 _maximumKilobytes = _maximumKilobytes / kiloByte;1063 newLog.MaximumKilobytes = _maximumKilobytes;1064 }1065 }1066 }1067 }1068 catch (InvalidOperationException ex)1069 {1070 WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, logname, computer);1071 continue;1072 }1073 catch (System.IO.IOException ex)1074 {1075 WriteNonTerminatingError(ex, EventlogResources.PathDoesNotExist, "PathDoesNotExist", ErrorCategory.InvalidOperation, null, computer);1076 continue;1077 }1078 catch (ArgumentOutOfRangeException ex)1079 {1080 if (!_retentionSpecified && !_maxkbSpecified)1081 {1082 WriteNonTerminatingError(ex, EventlogResources.InvalidArgument, "InvalidArgument", ErrorCategory.InvalidData, null, null);1083 }1084 else1085 {1086 WriteNonTerminatingError(ex, EventlogResources.ValueOutofRange, "ValueOutofRange", ErrorCategory.InvalidData, null, null);1087 }1088 1089 continue;1090 }1091 }1092 }1093 }1094 #endregion override1095 1096 }1097 #endregion LimitEventLogCommand1098 1099 #region ShowEventLogCommand1100 /// <summary>1101 /// This class implements the Show-EventLog command.1102 /// </summary>1103 1104 [Cmdlet(VerbsCommon.Show, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135257", RemotingCapability = RemotingCapability.SupportedByCommand)]1105 public sealed class ShowEventLogCommand : PSCmdlet1106 {1107 #region Parameters1108 1109 /// <summary>1110 /// Show eventviewer of this computer.1111 /// </summary>1112 [Parameter(Position = 0)]1113 [Alias("CN")]1114 [ValidateNotNullOrEmpty]1115 1116 public string ComputerName { get; set; } = ".";1117 1118 #endregion Parameters1119 1120 #region Overrides1121 1122 /// <summary>1123 /// Does the processing.1124 /// </summary>1125 protected override1126 void1127 BeginProcessing()1128 {1129 try1130 {1131 string eventVwrExe = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),1132 "eventvwr.exe");1133 Process.Start(eventVwrExe, ComputerName);1134 }1135 catch (Win32Exception e)1136 {1137 if (e.NativeErrorCode.Equals(0x00000002))1138 {1139 string message = StringUtil.Format(EventlogResources.NotSupported);1140 InvalidOperationException ex = new InvalidOperationException(message);1141 ErrorRecord er = new ErrorRecord(ex, "Win32Exception", ErrorCategory.InvalidOperation, null);1142 WriteError(er);1143 }1144 else1145 {1146 ErrorRecord er = new ErrorRecord(e, "Win32Exception", ErrorCategory.InvalidArgument, null);1147 WriteError(er);1148 }1149 }1150 catch (SystemException ex)1151 {1152 ErrorRecord er = new ErrorRecord(ex, "InvalidComputerName", ErrorCategory.InvalidArgument, ComputerName);1153 WriteError(er);1154 }1155 }1156 #endregion override1157 }1158 #endregion ShowEventLogCommand1159 1160 #region NewEventLogCommand1161 /// <summary>1162 /// This cmdlet creates the new event log .This cmdlet can also be used to1163 /// configure a new source for writing entries to an event log on the local1164 /// computer or a remote computer.1165 /// You can create an event source for an existing event log or a new event log.1166 /// When you create a new source for a new event log, the system registers the1167 /// source for that log, but the log is not created until the first entry is1168 /// written to it.1169 /// The operating system stores event logs as files. The associated file is1170 /// stored in the %SystemRoot%\System32\Config directory on the specified1171 /// computer. The file name is set by appending the first 8 characters of the1172 /// Log property with the ".evt" file name extension.1173 /// You can register the event source with localized resource file(s) for your1174 /// event category and message strings. Your application can write event log1175 /// entries using resource identifiers, rather than specifying the actual1176 /// string. You can register a separate file for event categories, messages and1177 /// parameter insertion strings, or you can register the same resource file for1178 /// all three types of strings.1179 /// </summary>1180 1181 [Cmdlet(VerbsCommon.New, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135235", RemotingCapability = RemotingCapability.SupportedByCommand)]1182 public class NewEventLogCommand : PSCmdlet1183 {1184 #region Parameter1185 /// <summary>1186 /// The following is the definition of the input parameter "CategoryResourceFile".1187 /// Specifies the path of the resource file that contains category strings for1188 /// the source1189 /// Resource File is expected to be present in Local/Remote Machines.1190 /// </summary>1191 [Parameter]1192 [ValidateNotNullOrEmpty]1193 [Alias("CRF")]1194 public string CategoryResourceFile { get; set; }1195 1196 /// <summary>1197 /// The following is the definition of the input parameter "ComputerName".1198 /// Specify the Computer Name. The default is local computer.1199 /// </summary>1200 [Parameter(Position = 2)]