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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Globalization;
using System.Management;
using System.Management.Automation;
using System.Text;
using System.Threading;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// A command to get WMI Objects.
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "WmiObject", DefaultParameterSetName = "query",
        HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113337", RemotingCapability = RemotingCapability.OwnedByCommand)]
    public class GetWmiObjectCommand : WmiBaseCmdlet
    {
        #region Parameters

        /// <summary>
        /// The WMI class to query.
        /// </summary>
        [Alias("ClassName")]
        [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")]
        [Parameter(Position = 1, ParameterSetName = "list")]
        [ValidateNotNullOrEmpty]
        public string Class { get; set; }

        /// <summary>
        /// To specify whether to get the results recursively.
        /// </summary>
        [Parameter(ParameterSetName = "list")]
        public SwitchParameter Recurse { get; set; } = false;

        /// <summary>
        /// The WMI properties to retrieve.
        /// </summary>
        [Parameter(Position = 1, ParameterSetName = "query")]
        [ValidateNotNullOrEmpty]
        public string[] Property
        {
            get { return (string[])_property.Clone(); }

            set { _property = value; }
        }

        /// <summary>
        /// The filter to be used in the search.
        /// </summary>
        [Parameter(ParameterSetName = "query")]
        public string Filter { get; set; }

        /// <summary>
        /// If Amended qualifier to use.
        /// </summary>
        [Parameter]
        public SwitchParameter Amended { get; set; }

        /// <summary>
        /// If Enumerate Deep flag to use. When 'list' parameter is specified 'EnumerateDeep' parameter is ignored.
        /// </summary>
        [Parameter(ParameterSetName = "WQLQuery")]
        [Parameter(ParameterSetName = "query")]
        public SwitchParameter DirectRead { get; set; }

        /// <summary>
        /// The list of classes.
        /// </summary>
        [Parameter(ParameterSetName = "list")]
        public SwitchParameter List { get; set; } = false;

        /// <summary>
        /// The query string to search for objects.
        /// </summary>
        [Parameter(Mandatory = true, ParameterSetName = "WQLQuery")]
        public string Query { get; set; }

        #endregion Parameters

        #region parameter data

        private string[] _property = new string[] { "*" };

        #endregion parameter data

        #region Command code

        /// <summary>
        /// Uses this.filter, this.wmiClass and this.property to retrieve the filter.
        /// </summary>
        internal string GetQueryString()
        {
            StringBuilder returnValue = new StringBuilder("select ");
            returnValue.Append(string.Join(", ", _property));
            returnValue.Append(" from ");
            returnValue.Append(Class);
            if (!string.IsNullOrEmpty(Filter))
            {
                returnValue.Append(" where ");
                returnValue.Append(Filter);
            }

            return returnValue.ToString();
        }
        /// <summary>
        /// Uses filter table to convert the class into WMI understandable language.
        ///            Character   Description Example Match   Comment
        ///             *   Matches zero or more characters starting at the specified position  A*  A,ag,Apple  Supported by PowerShell.
        ///              ?   Matches any character at the specified position ?n  An,in,on (does not match ran)   Supported by PowerShell.
        ///              _   Matches any character at the specified position    _n  An,in,on (does not match ran)   Supported by WMI
        ///             %   Matches zero or more characters starting at the specified position   A%  A,ag,Apple  Supported by WMI
        ///             []  Matches a range of characters  [a-l]ook    Book,cook,look (does not match took)    Supported by WMI and powershell
        ///              []  Matches specified characters   [bc]ook Book,cook, (does not match look)    Supported by WMI and powershell
        ///              ^   Does not Match specified characters. [^bc]ook    Look, took (does not match book, cook)  Supported by WMI.
        /// </summary>

        internal string GetFilterClassName()
        {
            if (string.IsNullOrEmpty(this.Class))
                return string.Empty;
            string filterClass = string.Copy(this.Class);
            filterClass = filterClass.Replace('*', '%');
            filterClass = filterClass.Replace('?', '_');
            return filterClass;
        }

        internal bool IsLocalizedNamespace(string sNamespace)
        {
            bool toReturn = false;
            if (sNamespace.StartsWith("ms_", StringComparison.OrdinalIgnoreCase))
            {
                toReturn = true;
            }

            return toReturn;
        }

        internal bool ValidateClassFormat()
        {
            string filterClass = this.Class;
            if (string.IsNullOrEmpty(filterClass))
                return true;
            StringBuilder newClassName = new StringBuilder();
            for (int i = 0; i < filterClass.Length; i++)
            {
                if (char.IsLetterOrDigit(filterClass[i]) ||
                    filterClass[i].Equals('[') || filterClass[i].Equals(']') ||
                    filterClass[i].Equals('*') || filterClass[i].Equals('?') ||
                    filterClass[i].Equals('-'))
                {
                    newClassName.Append(filterClass[i]);
                    continue;
                }
                else if (filterClass[i].Equals('_'))
                {
                    newClassName.Append('[');
                    newClassName.Append(filterClass[i]);
                    newClassName.Append(']');
                    continue;
                }

                return false;
            }

            this.Class = newClassName.ToString();
            return true;
        }

        /// <summary>
        /// Gets the ManagementObjectSearcher object.
        /// </summary>
        internal ManagementObjectSearcher GetObjectList(ManagementScope scope)
        {
            StringBuilder queryStringBuilder = new StringBuilder();
            if (string.IsNullOrEmpty(this.Class))
            {
                queryStringBuilder.Append("select * from meta_class");
            }
            else
            {
                string filterClass = GetFilterClassName();
                if (filterClass == null)
                    return null;
                queryStringBuilder.Append("select * from meta_class where __class like '");
                queryStringBuilder.Append(filterClass);
                queryStringBuilder.Append("'");
            }

            ObjectQuery classQuery = new ObjectQuery(queryStringBuilder.ToString());

            EnumerationOptions enumOptions = new EnumerationOptions();
            enumOptions.EnumerateDeep = true;
            enumOptions.UseAmendedQualifiers = this.Amended;
            var searcher = new ManagementObjectSearcher(scope, classQuery, enumOptions);
            return searcher;
        }
        /// <summary>
        /// Gets the properties of an item at the specified path.
        /// </summary>
        protected override void BeginProcessing()
        {
            ConnectionOptions options = GetConnectionOption();
            if (this.AsJob)
            {
                RunAsJob("Get-WMIObject");
                return;
            }
            else
            {
                if (List.IsPresent)
                {
                    if (!this.ValidateClassFormat())
                    {
                        ErrorRecord errorRecord = new ErrorRecord(
                       new ArgumentException(
                           string.Format(
                               Thread.CurrentThread.CurrentCulture,
                               "Class", this.Class)),
                       "INVALID_QUERY_IDENTIFIER",
                       ErrorCategory.InvalidArgument,
                       null);
                        errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiFilterInvalidClass", this.Class);

                        WriteError(errorRecord);
                        return;
                    }

                    foreach (string name in ComputerName)
                    {
                        if (this.Recurse.IsPresent)
                        {
                            Queue namespaceElement = new Queue();
                            namespaceElement.Enqueue(this.Namespace);
                            while (namespaceElement.Count > 0)
                            {
                                string connectNamespace = (string)namespaceElement.Dequeue();
                                ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, connectNamespace), options);
                                try
                                {
                                    scope.Connect();
                                }
                                catch (ManagementException e)
                                {
                                    ErrorRecord errorRecord = new ErrorRecord(
                                         e,
                                         "INVALID_NAMESPACE_IDENTIFIER",
                                         ErrorCategory.ObjectNotFound,
                                         null);
                                    errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message);
                                    WriteError(errorRecord);
                                    continue;
                                }
                                catch (System.Runtime.InteropServices.COMException e)
                                {
                                    ErrorRecord errorRecord = new ErrorRecord(
                                         e,
                                         "INVALID_NAMESPACE_IDENTIFIER",
                                         ErrorCategory.ObjectNotFound,
                                         null);
                                    errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message);
                                    WriteError(errorRecord);
                                    continue;
                                }
                                catch (System.UnauthorizedAccessException e)
                                {
                                    ErrorRecord errorRecord = new ErrorRecord(
                                         e,
                                         "INVALID_NAMESPACE_IDENTIFIER",
                                         ErrorCategory.ObjectNotFound,
                                         null);
                                    errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message);
                                    WriteError(errorRecord);
                                    continue;
                                }

                                ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions());
                                foreach (ManagementBaseObject obj in namespaceClass.GetInstances())
                                {
                                    if (!IsLocalizedNamespace((string)obj["Name"]))
                                    {
                                        namespaceElement.Enqueue(connectNamespace + "\\" + obj["Name"]);
                                    }
                                }

                                ManagementObjectSearcher searcher = this.GetObjectList(scope);
                                if (searcher == null)
                                    continue;
                                foreach (ManagementBaseObject obj in searcher.Get())
                                {
                                    WriteObject(obj);
                                }
                            }
                        }
                        else
                        {
                            ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options);
                            try
                            {
                                scope.Connect();
                            }
                            catch (ManagementException e)
                            {
                                ErrorRecord errorRecord = new ErrorRecord(
                                     e,
                                     "INVALID_NAMESPACE_IDENTIFIER",
                                     ErrorCategory.ObjectNotFound,
                                     null);
                                errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message);
                                WriteError(errorRecord);
                                continue;
                            }
                            catch (System.Runtime.InteropServices.COMException e)
                            {
                                ErrorRecord errorRecord = new ErrorRecord(
                                     e,
                                     "INVALID_NAMESPACE_IDENTIFIER",
                                     ErrorCategory.ObjectNotFound,
                                     null);
                                errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message);
                                WriteError(errorRecord);
                                continue;
                            }
                            catch (System.UnauthorizedAccessException e)
                            {
                                ErrorRecord errorRecord = new ErrorRecord(
                                     e,
                                     "INVALID_NAMESPACE_IDENTIFIER",
                                     ErrorCategory.ObjectNotFound,
                                     null);
                                errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message);
                                WriteError(errorRecord);
                                continue;
                            }

                            ManagementObjectSearcher searcher = this.GetObjectList(scope);
                            if (searcher == null)
                                continue;
                            foreach (ManagementBaseObject obj in searcher.Get())
                            {
                                WriteObject(obj);
                            }
                        }
                    }

                    return;
                }

                // When -List is not specified and -Recurse is specified, we need the -Class parameter to compose the right query string
                if (this.Recurse.IsPresent && string.IsNullOrEmpty(Class))
                {
                    string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, "-Class");
                    ErrorRecord er = new ErrorRecord(new InvalidOperationException(errorMsg), "InvalidOperationException", ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                string queryString = string.IsNullOrEmpty(this.Query) ? GetQueryString() : this.Query;
                ObjectQuery query = new ObjectQuery(queryString.ToString());

                foreach (string name in ComputerName)
                {
                    try
                    {
                        ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options);
                        EnumerationOptions enumOptions = new EnumerationOptions();
                        enumOptions.UseAmendedQualifiers = Amended;
                        enumOptions.DirectRead = DirectRead;
                        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions);
                        foreach (ManagementBaseObject obj in searcher.Get())
                        {
                            WriteObject(obj);
                        }
                    }
                    catch (ManagementException e)
                    {
                        ErrorRecord errorRecord = null;
                        if (e.ErrorCode.Equals(ManagementStatus.InvalidClass))
                        {
                            string className = GetClassNameFromQuery(queryString);
                            string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure,
                                                        e.Message, className);
                            errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidType, null);
                        }
                        else if (e.ErrorCode.Equals(ManagementStatus.InvalidQuery))
                        {
                            string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure,
                                                        e.Message, queryString);
                            errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null);
                        }
                        else if (e.ErrorCode.Equals(ManagementStatus.InvalidNamespace))
                        {
                            string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure,
                                                        e.Message, this.Namespace);
                            errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null);
                        }
                        else
                        {
                            errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null);
                        }

                        WriteError(errorRecord);
                        continue;
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "GetWMICOMException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                        continue;
                    }
                }
            }
        }

        /// <summary>
        /// Get the class name from a query string.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private string GetClassNameFromQuery(string query)
        {
            System.Management.Automation.Diagnostics.Assert(query.Contains("from"),
                                                            "Only get called when ErrorCode is InvalidClass, which means the query string contains 'from' and the class name");

            if (Class != null)
            {
                return Class;
            }

            int fromIndex = query.IndexOf(" from ", StringComparison.OrdinalIgnoreCase);
            string subQuery = query.Substring(fromIndex + " from ".Length);
            string className = subQuery.Split(' ')[0];
            return className;
        }

        #endregion Command code
    }
}