File size: 7,557 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if !UNIX

using System;
using System.Diagnostics.CodeAnalysis;
using System.Management;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Security.Principal;
using System.Text;

namespace Microsoft.PowerShell.Commands
{
    #region Get-HotFix

    /// <summary>
    /// Cmdlet for Get-Hotfix Proxy.
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "HotFix", DefaultParameterSetName = "Default",
        HelpUri = "https://go.microsoft.com/fwlink/?linkid=2109716", RemotingCapability = RemotingCapability.SupportedByCommand)]
    [OutputType(@"System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering")]
    public sealed class GetHotFixCommand : PSCmdlet, IDisposable
    {
        #region Parameters

        /// <summary>
        /// Specifies the HotFixID. Unique identifier associated with a particular update.
        /// </summary>
        [Parameter(Position = 0, ParameterSetName = "Default")]
        [ValidateNotNullOrEmpty]
        [Alias("HFID")]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public string[] Id { get; set; }

        /// <summary>
        /// To search on description of Hotfixes.
        /// </summary>
        [Parameter(ParameterSetName = "Description")]
        [ValidateNotNullOrEmpty]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public string[] Description { get; set; }

        /// <summary>
        /// Parameter to pass the Computer Name.
        /// </summary>
        [Parameter(ValueFromPipelineByPropertyName = true)]
        [ValidateNotNullOrEmpty]
        [Alias("CN", "__Server", "IPAddress")]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public string[] ComputerName { get; set; } = new string[] { "localhost" };

        /// <summary>
        /// Parameter to pass the Credentials.
        /// </summary>
        [Parameter]
        [Credential]
        [ValidateNotNullOrEmpty]
        public PSCredential Credential { get; set; }

        #endregion Parameters

        #region Overrides

        private ManagementObjectSearcher _searchProcess;

        private bool _inputContainsWildcard = false;
        private readonly ConnectionOptions _connectionOptions = new();

        /// <summary>
        /// Sets connection options.
        /// </summary>
        protected override void BeginProcessing()
        {
            _connectionOptions.Authentication = AuthenticationLevel.Packet;
            _connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
            _connectionOptions.Username = Credential?.UserName;
            _connectionOptions.SecurePassword = Credential?.Password;
        }

        /// <summary>
        /// Get the List of HotFixes installed on the Local Machine.
        /// </summary>
        protected override void ProcessRecord()
        {
            foreach (string computer in ComputerName)
            {
                bool foundRecord = false;
                StringBuilder queryString = new();
                ManagementScope scope = new(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), _connectionOptions);
                scope.Connect();
                if (Id != null)
                {
                    queryString.Append("Select * from Win32_QuickFixEngineering where (");
                    for (int i = 0; i <= Id.Length - 1; i++)
                    {
                        queryString.Append("HotFixID= '");
                        queryString.Append(Id[i].Replace("'", "\\'"));
                        queryString.Append('\'');
                        if (i < Id.Length - 1)
                        {
                            queryString.Append(" Or ");
                        }
                    }

                    queryString.Append(')');
                }
                else
                {
                    queryString.Append("Select * from Win32_QuickFixEngineering");
                    foundRecord = true;
                }

                _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(queryString.ToString()));
                foreach (ManagementObject obj in _searchProcess.Get())
                {
                    if (Description != null)
                    {
                        if (!FilterMatch(obj))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        _inputContainsWildcard = true;
                    }

                    // try to translate the SID to a more friendly username
                    // just stick with the SID if anything goes wrong
                    string installed = (string)obj["InstalledBy"];
                    if (!string.IsNullOrEmpty(installed))
                    {
                        try
                        {
                            SecurityIdentifier secObj = new(installed);
                            obj["InstalledBy"] = secObj.Translate(typeof(NTAccount));
                        }
                        catch (IdentityNotMappedException)
                        {
                            // thrown by SecurityIdentifier.Translate
                        }
                        catch (SystemException)
                        {
                            // thrown by SecurityIdentifier.constr
                        }
                    }

                    WriteObject(obj);
                    foundRecord = true;
                }

                if (!foundRecord && !_inputContainsWildcard)
                {
                    Exception ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer));
                    WriteError(new ErrorRecord(ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null));
                }

                if (_searchProcess != null)
                {
                    this.Dispose();
                }
            }
        }

        /// <summary>
        /// To implement ^C.
        /// </summary>
        protected override void StopProcessing()
        {
            _searchProcess?.Dispose();
        }
        #endregion Overrides

        #region "Private Methods"

        private bool FilterMatch(ManagementObject obj)
        {
            try
            {
                foreach (string desc in Description)
                {
                    WildcardPattern wildcardpattern = WildcardPattern.Get(desc, WildcardOptions.IgnoreCase);
                    if (wildcardpattern.IsMatch((string)obj["Description"]))
                    {
                        return true;
                    }

                    if (WildcardPattern.ContainsWildcardCharacters(desc))
                    {
                        _inputContainsWildcard = true;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }

            return false;
        }

        #endregion "Private Methods"

        #region "IDisposable Members"

        /// <summary>
        /// Release all resources.
        /// </summary>
        public void Dispose()
        {
            _searchProcess?.Dispose();
        }

        #endregion "IDisposable Members"
    }
    #endregion
}

#endif