File size: 23,873 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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Resources;
using System.Threading;
using Microsoft.Powershell.Commands.GetCounter.PdhNative;
using Microsoft.PowerShell.Commands.Diagnostics.Common;
using Microsoft.PowerShell.Commands.GetCounter;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// Class that implements the Get-Counter cmdlet.
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109647")]
    public sealed class GetCounterCommand : PSCmdlet
    {
        //
        // ListSet parameter
        //
        [Parameter(
                Position = 0,
                Mandatory = true,
                ParameterSetName = "ListSetSet",
                ValueFromPipeline = true,
                ValueFromPipelineByPropertyName = false,
                HelpMessageBaseName = "GetEventResources")]
        [AllowEmptyCollection]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
                            Scope = "member",
                            Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
                            Justification = "A string[] is required here because that is the type Powershell supports")]
        public string[] ListSet { get; set; } = { "*" };

        //
        // Counter parameter
        //
        [Parameter(
                Position = 0,
                ParameterSetName = "GetCounterSet",
                ValueFromPipeline = true,
                ValueFromPipelineByPropertyName = true,
                HelpMessageBaseName = "GetEventResources")]
        [AllowEmptyCollection]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
                            Scope = "member",
                            Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ListSet",
                            Justification = "A string[] is required here because that is the type Powershell supports")]
        public string[] Counter
        {
            get
            {
                return _counter;
            }

            set
            {
                _counter = value;
                _defaultCounters = false;
            }
        }

        private string[] _counter = {@"\network interface(*)\bytes total/sec",
                                 @"\processor(_total)\% processor time",
                                 @"\memory\% committed bytes in use",
                                 @"\memory\cache faults/sec",
                                 @"\physicaldisk(_total)\% disk time",
                                 @"\physicaldisk(_total)\current disk queue length"};

        private bool _defaultCounters = true;

        private readonly List<string> _accumulatedCounters = new();

        //
        // SampleInterval parameter.
        // Defaults to 1 second.
        //
        [Parameter(
                ParameterSetName = "GetCounterSet",
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                HelpMessageBaseName = "GetEventResources")]
        [ValidateRange((int)1, int.MaxValue)]
        public int SampleInterval { get; set; } = 1;

        //
        // MaxSamples parameter
        //
        private const Int64 KEEP_ON_SAMPLING = -1;

        [Parameter(
                ParameterSetName = "GetCounterSet",
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                HelpMessageBaseName = "GetEventResources")]
        [ValidateRange((Int64)1, Int64.MaxValue)]
        public Int64 MaxSamples
        {
            get
            {
                return _maxSamples;
            }

            set
            {
                _maxSamples = value;
                _maxSamplesSpecified = true;
            }
        }

        private Int64 _maxSamples = 1;
        private bool _maxSamplesSpecified = false;

        //
        // Continuous switch
        //
        [Parameter(ParameterSetName = "GetCounterSet")]
        public SwitchParameter Continuous
        {
            get { return _continuous; }

            set { _continuous = value; }
        }

        private bool _continuous = false;

        //
        // ComputerName parameter
        //
        [Parameter(
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                HelpMessageBaseName = "GetEventResources",
                HelpMessageResourceId = "ComputerNameParamHelp")]
        [ValidateNotNull]
        [AllowEmptyCollection]
        [Alias("Cn")]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
                            Scope = "member",
                            Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ComputerName",
                            Justification = "A string[] is required here because that is the type Powershell supports")]
        public string[] ComputerName { get; set; } = Array.Empty<string>();

        private ResourceManager _resourceMgr = null;

        private PdhHelper _pdhHelper = null;

        private readonly EventWaitHandle _cancelEventArrived = new(false, EventResetMode.ManualReset);

        // Culture identifier(s)
        private const string FrenchCultureId = "fr-FR";
        // The localized Pdh resource strings might use Unicode characters that are different from
        // what the user can type with the keyboard to represent a special character.
        //
        // e.g. the apostrophe in French UI culture: it's [char]39 from keyboard, but it's [char]8217
        // in the resource strings.
        //
        // With this dictionary, we can add special mapping if we find other special cases in the future.
        private readonly Dictionary<string, List<Tuple<char, char>>> _cultureAndSpecialCharacterMap =
            new()
                {
                   {
                       FrenchCultureId, new List<Tuple<char, char>>()
                                            {
                                                // 'APOSTROPHE' to 'RIGHT SINGLE QUOTATION MARK'
                                                new Tuple<char, char>((char)0x0027, (char)0x2019),
                                                // 'MODIFIER LETTER APOSTROPHE' to 'RIGHT SINGLE QUOTATION MARK'
                                                new Tuple<char, char>((char)0x02BC, (char)0x2019),
                                                // 'HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT' to 'RIGHT SINGLE QUOTATION MARK'
                                                new Tuple<char, char>((char)0x275C, (char)0x2019),
                                            }
                   }
                };

        //
        // BeginProcessing() is invoked once per pipeline
        //
        protected override void BeginProcessing()
        {
            if (Platform.IsIoT)
            {
                // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet.
                throw new PlatformNotSupportedException();
            }

            _pdhHelper = new PdhHelper();
            _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();

            uint res = _pdhHelper.ConnectToDataSource();
            if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
            {
                ReportPdhError(res, true);
                return;
            }

            if (Continuous.IsPresent && _maxSamplesSpecified)
            {
                Exception exc = new(string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterContinuousOrMaxSamples")));
                ThrowTerminatingError(new ErrorRecord(exc, "CounterContinuousOrMaxSamples", ErrorCategory.InvalidArgument, null));
            }
        }

        //
        // EndProcessing() is invoked once per pipeline
        //
        protected override void EndProcessing()
        {
            if (ParameterSetName == "GetCounterSet")
            {
                ProcessGetCounter();
            }

            _pdhHelper.Dispose();
        }

        //
        // Handle Control-C
        //
        protected override void StopProcessing()
        {
            _cancelEventArrived.Set();
            _pdhHelper.Dispose();
        }

        //
        // ProcessRecord() override.
        // This is the main entry point for the cmdlet.
        //
        protected override void ProcessRecord()
        {
            try
            {
                switch (ParameterSetName)
                {
                    case "ListSetSet":
                        ProcessListSet();
                        break;

                    case "GetCounterSet":
                        AccumulatePipelineCounters();
                        break;

                    default:
                        Debug.Fail(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}"));
                        break;
                }
            }
            catch (Exception exc)
            {
                ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
            }
        }

        //
        // AccumulatePipelineCounters() accumulates counter paths in the pipeline scenario:
        // we do not want to start sampling until all the counters are supplied.
        //
        private void AccumulatePipelineCounters()
        {
            _accumulatedCounters.AddRange(_counter);
        }

        //
        // ProcessListSet() does the work to process ListSet parameter set.
        //
        private void ProcessListSet()
        {
            if (ComputerName.Length == 0)
            {
                ProcessListSetPerMachine(null);
            }
            else
                foreach (string machine in ComputerName)
                {
                    ProcessListSetPerMachine(machine);
                }
        }

        //
        // ProcessListSetPerMachine() helper lists counter sets on a machine.
        // NOTE: machine argument should be NULL for the local machine
        //
        private void ProcessListSetPerMachine(string machine)
        {
            StringCollection counterSets = new();
            uint res = _pdhHelper.EnumObjects(machine, ref counterSets);
            if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
            {
                // add an error message
                string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoCounterSetsOnComputer"), machine, res);
                Exception exc = new(msg);
                WriteError(new ErrorRecord(exc, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine));
                return;
            }

            CultureInfo culture = GetCurrentCulture();
            List<Tuple<char, char>> characterReplacementList = null;
            StringCollection validPaths = new();

            _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList);

            foreach (string pattern in ListSet)
            {
                bool bMatched = false;
                string normalizedPattern = pattern;

                if (characterReplacementList != null)
                {
                    foreach (Tuple<char, char> pair in characterReplacementList)
                    {
                        normalizedPattern = normalizedPattern.Replace(pair.Item1, pair.Item2);
                    }
                }

                WildcardPattern wildLogPattern = new(normalizedPattern, WildcardOptions.IgnoreCase);

                foreach (string counterSet in counterSets)
                {
                    if (!wildLogPattern.IsMatch(counterSet))
                    {
                        continue;
                    }

                    StringCollection counterSetCounters = new();
                    StringCollection counterSetInstances = new();

                    res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances);
                    if (res == PdhResults.PDH_ACCESS_DENIED)
                    {
                        string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSetEnumAccessDenied"), counterSet);
                        Exception exc = new(msg);
                        WriteError(new ErrorRecord(exc, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null));
                        continue;
                    }
                    else if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
                    {
                        ReportPdhError(res, false);
                        continue;
                    }

                    string[] instanceArray = new string[counterSetInstances.Count];
                    int i = 0;
                    foreach (string instance in counterSetInstances)
                    {
                        instanceArray[i++] = instance;
                    }

                    //
                    // Special case: no instances present: change to * to create a valid paths
                    //
                    if (instanceArray.Length == 1 &&
                        instanceArray[0].Length == 0)
                    {
                        instanceArray[0] = "*";
                    }

                    Dictionary<string, string[]> counterInstanceMapping = new();
                    foreach (string counter in counterSetCounters)
                    {
                        counterInstanceMapping.TryAdd(counter, instanceArray);
                    }

                    PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
                    if (counterSetInstances.Count > 1)
                    {
                        categoryType = PerformanceCounterCategoryType.MultiInstance;
                    }
                    else // if (counterSetInstances.Count == 1) //???
                    {
                        categoryType = PerformanceCounterCategoryType.SingleInstance;
                    }

                    string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet);

                    CounterSet setObj = new(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping);
                    WriteObject(setObj);
                    bMatched = true;
                }

                if (!bMatched)
                {
                    string msg = _resourceMgr.GetString("NoMatchingCounterSetsFound");
                    Exception exc = new(string.Format(CultureInfo.InvariantCulture, msg,
                      machine ?? "localhost", normalizedPattern));
                    WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null));
                }
            }
        }

        //
        // ProcessGetCounter()
        // Does the work to process GetCounterSet parameter set.
        //
        private void ProcessGetCounter()
        {
            // 1. Combine machine names with paths, if needed, to construct full paths
            // 2. Translate default paths into current locale
            // 3. Expand wildcards and validate the paths and write errors for any invalid paths
            // 4. OpenQuery/ AddCounters
            // 5. Skip the first reading

            CultureInfo culture = GetCurrentCulture();
            List<Tuple<char, char>> characterReplacementList = null;
            List<string> paths = CombineMachinesAndCounterPaths();

            if (!_defaultCounters)
            {
                _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList);
            }

            StringCollection allExpandedPaths = new();
            uint res;
            foreach (string path in paths)
            {
                string localizedPath = path;
                if (_defaultCounters)
                {
                    res = _pdhHelper.TranslateLocalCounterPath(path, out localizedPath);
                    if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
                    {
                        string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathTranslationFailed"), res);
                        Exception exc = new(msg);
                        WriteError(new ErrorRecord(exc, "CounterPathTranslationFailed", ErrorCategory.InvalidResult, null));

                        localizedPath = path;
                    }
                }
                else if (characterReplacementList != null)
                {
                    foreach (Tuple<char, char> pair in characterReplacementList)
                    {
                        localizedPath = localizedPath.Replace(pair.Item1, pair.Item2);
                    }
                }

                StringCollection expandedPaths;
                res = _pdhHelper.ExpandWildCardPath(localizedPath, out expandedPaths);
                if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
                {
                    WriteDebug("Could not expand path " + localizedPath);
                    ReportPdhError(res, false);
                    continue;
                }

                foreach (string expandedPath in expandedPaths)
                {
                    if (!_pdhHelper.IsPathValid(expandedPath))
                    {
                        string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathIsInvalid"), localizedPath);
                        Exception exc = new(msg);
                        WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null));

                        continue;
                    }

                    allExpandedPaths.Add(expandedPath);
                }
            }

            if (allExpandedPaths.Count == 0)
            {
                return;
            }

            res = _pdhHelper.OpenQuery();
            if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
            {
                ReportPdhError(res, false);
            }

            res = _pdhHelper.AddCounters(ref allExpandedPaths, true);
            if (res != PdhResults.PDH_CSTATUS_VALID_DATA)
            {
                ReportPdhError(res, true);

                return;
            }

            PerformanceCounterSampleSet nextSet;

            bool bSkip = true;
            uint sampleReads = 0;

            if (Continuous.IsPresent)
            {
                _maxSamples = KEEP_ON_SAMPLING;
            }

            while (true)
            {
                // read the first set just to get the initial values
                res = _pdhHelper.ReadNextSet(out nextSet, bSkip);

                if (res == PdhResults.PDH_CSTATUS_VALID_DATA)
                {
                    // Display valid data
                    if (!bSkip)
                    {
                        WriteSampleSetObject(nextSet);
                        sampleReads++;
                    }

                    // Don't need to skip anymore
                    bSkip = false;
                }
                else if (res == PdhResults.PDH_NO_DATA || res == PdhResults.PDH_INVALID_DATA)
                {
                    // The provider may not be running.
                    // We should keep on trying - but skip the next valid reading.

                    ReportPdhError(res, false);

                    bSkip = true;

                    // Count this failed attempt as a sample:
                    sampleReads++;
                }
                else
                {
                    // Unexpected error, return
                    ReportPdhError(res, true);
                    return;
                }

                if (_maxSamples != KEEP_ON_SAMPLING && sampleReads >= _maxSamples)
                {
                    break;
                }

                bool cancelled = _cancelEventArrived.WaitOne((int)SampleInterval * 1000, true);
                if (cancelled)
                {
                    break;
                }
            }
        }

        private void ReportPdhError(uint res, bool bTerminate)
        {
            string msg;
            uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg);
            if (formatRes != 0)
            {
                msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res);
            }

            Exception exc = new(msg);
            if (bTerminate)
            {
                ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
            }
            else
            {
                WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
            }
        }

        //
        // CombineMachinesAndCounterPaths() helper.
        // For paths that do not contain machine names, creates a path for each machine in machineNames.
        // Paths already containing a machine name will be preserved.
        //
        private List<string> CombineMachinesAndCounterPaths()
        {
            List<string> retColl = new();

            if (ComputerName.Length == 0)
            {
                retColl.AddRange(_accumulatedCounters);
                return retColl;
            }

            foreach (string path in _accumulatedCounters)
            {
                if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) // NOTE: can we do anything smarter here?
                {
                    retColl.Add(path);
                }
                else
                {
                    foreach (string machine in ComputerName)
                    {
                        string slashBeforePath = path.Length > 0 && path[0] == '\\' ? string.Empty : "\\";
                        if (machine.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase))
                        {
                            retColl.Add(machine + slashBeforePath + path);
                        }
                        else
                        {
                            retColl.Add("\\\\" + machine + slashBeforePath + path);
                        }
                    }
                }
            }

            return retColl;
        }

        //
        // WriteSampleSetObject() helper.
        // In addition to writing the PerformanceCounterSampleSet object,
        // it writes a single error if one of the samples has an invalid (non-zero) status.
        //
        private void WriteSampleSetObject(PerformanceCounterSampleSet set)
        {
            foreach (PerformanceCounterSample sample in set.CounterSamples)
            {
                if (sample.Status != 0)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid"));
                    Exception exc = new(msg);
                    WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
                    break;
                }
            }

            WriteObject(set);
        }

        private static CultureInfo GetCurrentCulture()
        {
            return Thread.CurrentThread.CurrentUICulture;
        }
    }
}