MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4#if !UNIX5 6using System;7using System.Diagnostics.CodeAnalysis;8using System.Management;9using System.Management.Automation;10using System.Management.Automation.Internal;11using System.Security.Principal;12using System.Text;13 14namespace Microsoft.PowerShell.Commands15{16 #region Get-HotFix17 18 /// <summary>19 /// Cmdlet for Get-Hotfix Proxy.20 /// </summary>21 [Cmdlet(VerbsCommon.Get, "HotFix", DefaultParameterSetName = "Default",22 HelpUri = "https://go.microsoft.com/fwlink/?linkid=2109716", RemotingCapability = RemotingCapability.SupportedByCommand)]23 [OutputType(@"System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering")]24 public sealed class GetHotFixCommand : PSCmdlet, IDisposable25 {26 #region Parameters27 28 /// <summary>29 /// Specifies the HotFixID. Unique identifier associated with a particular update.30 /// </summary>31 [Parameter(Position = 0, ParameterSetName = "Default")]32 [ValidateNotNullOrEmpty]33 [Alias("HFID")]34 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]35 public string[] Id { get; set; }36 37 /// <summary>38 /// To search on description of Hotfixes.39 /// </summary>40 [Parameter(ParameterSetName = "Description")]41 [ValidateNotNullOrEmpty]42 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]43 public string[] Description { get; set; }44 45 /// <summary>46 /// Parameter to pass the Computer Name.47 /// </summary>48 [Parameter(ValueFromPipelineByPropertyName = true)]49 [ValidateNotNullOrEmpty]50 [Alias("CN", "__Server", "IPAddress")]51 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]52 public string[] ComputerName { get; set; } = new string[] { "localhost" };53 54 /// <summary>55 /// Parameter to pass the Credentials.56 /// </summary>57 [Parameter]58 [Credential]59 [ValidateNotNullOrEmpty]60 public PSCredential Credential { get; set; }61 62 #endregion Parameters63 64 #region Overrides65 66 private ManagementObjectSearcher _searchProcess;67 68 private bool _inputContainsWildcard = false;69 private readonly ConnectionOptions _connectionOptions = new();70 71 /// <summary>72 /// Sets connection options.73 /// </summary>74 protected override void BeginProcessing()75 {76 _connectionOptions.Authentication = AuthenticationLevel.Packet;77 _connectionOptions.Impersonation = ImpersonationLevel.Impersonate;78 _connectionOptions.Username = Credential?.UserName;79 _connectionOptions.SecurePassword = Credential?.Password;80 }81 82 /// <summary>83 /// Get the List of HotFixes installed on the Local Machine.84 /// </summary>85 protected override void ProcessRecord()86 {87 foreach (string computer in ComputerName)88 {89 bool foundRecord = false;90 StringBuilder queryString = new();91 ManagementScope scope = new(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), _connectionOptions);92 scope.Connect();93 if (Id != null)94 {95 queryString.Append("Select * from Win32_QuickFixEngineering where (");96 for (int i = 0; i <= Id.Length - 1; i++)97 {98 queryString.Append("HotFixID= '");99 queryString.Append(Id[i].Replace("'", "\\'"));100 queryString.Append('\'');101 if (i < Id.Length - 1)102 {103 queryString.Append(" Or ");104 }105 }106 107 queryString.Append(')');108 }109 else110 {111 queryString.Append("Select * from Win32_QuickFixEngineering");112 foundRecord = true;113 }114 115 _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(queryString.ToString()));116 foreach (ManagementObject obj in _searchProcess.Get())117 {118 if (Description != null)119 {120 if (!FilterMatch(obj))121 {122 continue;123 }124 }125 else126 {127 _inputContainsWildcard = true;128 }129 130 // try to translate the SID to a more friendly username131 // just stick with the SID if anything goes wrong132 string installed = (string)obj["InstalledBy"];133 if (!string.IsNullOrEmpty(installed))134 {135 try136 {137 SecurityIdentifier secObj = new(installed);138 obj["InstalledBy"] = secObj.Translate(typeof(NTAccount));139 }140 catch (IdentityNotMappedException)141 {142 // thrown by SecurityIdentifier.Translate143 }144 catch (SystemException)145 {146 // thrown by SecurityIdentifier.constr147 }148 }149 150 WriteObject(obj);151 foundRecord = true;152 }153 154 if (!foundRecord && !_inputContainsWildcard)155 {156 Exception ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer));157 WriteError(new ErrorRecord(ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null));158 }159 160 if (_searchProcess != null)161 {162 this.Dispose();163 }164 }165 }166 167 /// <summary>168 /// To implement ^C.169 /// </summary>170 protected override void StopProcessing()171 {172 _searchProcess?.Dispose();173 }174 #endregion Overrides175 176 #region "Private Methods"177 178 private bool FilterMatch(ManagementObject obj)179 {180 try181 {182 foreach (string desc in Description)183 {184 WildcardPattern wildcardpattern = WildcardPattern.Get(desc, WildcardOptions.IgnoreCase);185 if (wildcardpattern.IsMatch((string)obj["Description"]))186 {187 return true;188 }189 190 if (WildcardPattern.ContainsWildcardCharacters(desc))191 {192 _inputContainsWildcard = true;193 }194 }195 }196 catch (Exception)197 {198 return false;199 }200 201 return false;202 }203 204 #endregion "Private Methods"205 206 #region "IDisposable Members"207 208 /// <summary>209 /// Release all resources.210 /// </summary>211 public void Dispose()212 {213 _searchProcess?.Dispose();214 }215 216 #endregion "IDisposable Members"217 }218 #endregion219}220 221#endif222 