File size: 13,072 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Xml;

using Microsoft.PowerShell.Commands.Diagnostics.Common;
using Microsoft.PowerShell.Commands.GetCounter;
using Microsoft.Powershell.Commands.GetCounter.PdhNative;

namespace Microsoft.PowerShell.Commands
{
    ///
    /// Class that implements the Get-Counter cmdlet.
    ///
    [Cmdlet(VerbsData.Export, "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138337")]
    public sealed class ExportCounterCommand : PSCmdlet
    {
        //
        // Path parameter
        //
        [Parameter(
                Mandatory = true,
                Position = 0,
                ValueFromPipelineByPropertyName = true,
                HelpMessageBaseName = "GetEventResources")]
        [Alias("PSPath")]

        public string Path
        {
            get { return _path; }

            set { _path = value; }
        }

        private string _path;
        private string _resolvedPath;

        //
        // Format parameter.
        // Valid strings are "blg", "csv", "tsv" (case-insensitive).
        //
        [Parameter(
                Mandatory = false,
                ValueFromPipeline = false,
                ValueFromPipelineByPropertyName = false,
                HelpMessageBaseName = "GetEventResources")]
        [ValidateNotNull]
        [ValidateSet("blg", "csv", "tsv")]
        public string FileFormat
        {
            get { return _format; }

            set { _format = value; }
        }

        private string _format = "blg";

        //
        // MaxSize parameter
        // Maximum output file size, in megabytes.
        //
        [Parameter(
                HelpMessageBaseName = "GetEventResources")]
        public UInt32 MaxSize
        {
            get { return _maxSize; }

            set { _maxSize = value; }
        }

        private UInt32 _maxSize = 0;

        //
        // InputObject parameter
        //
        [Parameter(
                Mandatory = true,
                ValueFromPipeline = true,
                ValueFromPipelineByPropertyName = true,
                HelpMessageBaseName = "GetEventResources")]

        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
                            Scope = "member",
                            Target = "Microsoft.PowerShell.Commands.ExportCounterCommand.InputObject",
                            Justification = "A PerformanceCounterSampleSet[] is required here because Powershell supports arrays natively.")]
        public PerformanceCounterSampleSet[] InputObject
        {
            get { return _counterSampleSets; }

            set { _counterSampleSets = value; }
        }

        private PerformanceCounterSampleSet[] _counterSampleSets = new PerformanceCounterSampleSet[0];

        //
        // Force switch
        //
        [Parameter(
                HelpMessageBaseName = "GetEventResources")]
        public SwitchParameter Force
        {
            get { return _force; }

            set { _force = value; }
        }

        private SwitchParameter _force;

        //
        // Circular switch
        //
        [Parameter(
                HelpMessageBaseName = "GetEventResources")]
        public SwitchParameter Circular
        {
            get { return _circular; }

            set { _circular = value; }
        }

        private SwitchParameter _circular;

        private ResourceManager _resourceMgr = null;

        private PdhHelper _pdhHelper = null;

        private bool _stopping = false;

        private bool _queryInitialized = false;

        private PdhLogFileType _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY;

        //
        // BeginProcessing() is invoked once per pipeline
        //
        protected override void BeginProcessing()
        {

#if CORECLR
            if (Platform.IsIoT)
            {
                // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet.
                throw new PlatformNotSupportedException();
            }

            // PowerShell 7 requires at least Windows 7,
            // so no version test is needed
            _pdhHelper = new PdhHelper(false);
#else
            //
            // Determine the OS version: this cmdlet requires Windows 7
            // because it uses new Pdh functionality.
            //
            Version osVersion = System.Environment.OSVersion.Version;
            if (osVersion.Major < 6 ||
                (osVersion.Major == 6 && osVersion.Minor < 1))
            {
                string msg = _resourceMgr.GetString("ExportCtrWin7Required");
                Exception exc = new Exception(msg);
                ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null));
            }

            _pdhHelper = new PdhHelper(osVersion.Major < 6);
#endif
            _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();

            //
            // Set output format (log file type)
            //
            SetOutputFormat();

            if (Circular.IsPresent && _maxSize == 0)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterCircularNoMaxSize"));
                Exception exc = new Exception(msg);
                WriteError(new ErrorRecord(exc, "CounterCircularNoMaxSize", ErrorCategory.InvalidResult, null));
            }

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

            res = _pdhHelper.OpenQuery();
            if (res != 0)
            {
                ReportPdhError(res, true);
            }
        }

        //
        // EndProcessing() is invoked once per pipeline
        //
        protected override void EndProcessing()
        {
            _pdhHelper.Dispose();
        }

        ///
        /// Handle Control-C
        ///
        protected override void StopProcessing()
        {
            _stopping = true;
            _pdhHelper.Dispose();
        }

        //
        // ProcessRecord() override.
        // This is the main entry point for the cmdlet.
        // When counter data comes from the pipeline, this gets invoked for each pipelined object.
        // When it's passed in as an argument, ProcessRecord() is called once for the entire _counterSampleSets array.
        //
        protected override void ProcessRecord()
        {
            Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] != null);

            ResolvePath();

            uint res = 0;

            if (!_queryInitialized)
            {
                if (_format.ToLowerInvariant().Equals("blg"))
                {
                    res = _pdhHelper.AddRelogCounters(_counterSampleSets[0]);
                }
                else
                {
                    res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[0]);
                }

                if (res != 0)
                {
                    ReportPdhError(res, true);
                }

                res = _pdhHelper.OpenLogForWriting(_resolvedPath, _outputFormat, Force.IsPresent, _maxSize * 1024 * 1024, Circular.IsPresent, null);
                if (res == PdhResults.PDH_FILE_ALREADY_EXISTS)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterFileExists"), _resolvedPath);
                    Exception exc = new Exception(msg);
                    ThrowTerminatingError(new ErrorRecord(exc, "CounterFileExists", ErrorCategory.InvalidResult, null));
                }
                else if (res == PdhResults.PDH_LOG_FILE_CREATE_ERROR)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileCreateFailed"), _resolvedPath);
                    Exception exc = new Exception(msg);
                    ThrowTerminatingError(new ErrorRecord(exc, "FileCreateFailed", ErrorCategory.InvalidResult, null));
                }
                else if (res == PdhResults.PDH_LOG_FILE_OPEN_ERROR)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileOpenFailed"), _resolvedPath);
                    Exception exc = new Exception(msg);
                    ThrowTerminatingError(new ErrorRecord(exc, "FileOpenFailed", ErrorCategory.InvalidResult, null));
                }
                else if (res != 0)
                {
                    ReportPdhError(res, true);
                }

                _queryInitialized = true;
            }

            foreach (PerformanceCounterSampleSet set in _counterSampleSets)
            {
                _pdhHelper.ResetRelogValues();

                foreach (PerformanceCounterSample sample in set.CounterSamples)
                {
                    bool bUnknownKey = false;
                    res = _pdhHelper.SetCounterValue(sample, out bUnknownKey);
                    if (bUnknownKey)
                    {
                        string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterExportSampleNotInInitialSet"), sample.Path, _resolvedPath);
                        Exception exc = new Exception(msg);
                        WriteError(new ErrorRecord(exc, "CounterExportSampleNotInInitialSet", ErrorCategory.InvalidResult, null));
                    }
                    else if (res != 0)
                    {
                        ReportPdhError(res, true);
                    }
                }

                res = _pdhHelper.WriteRelogSample(set.Timestamp);
                if (res != 0)
                {
                    ReportPdhError(res, true);
                }

                if (_stopping)
                {
                    break;
                }
            }
        }

        // Determines Log File Type based on FileFormat parameter
        //
        private void SetOutputFormat()
        {
            switch (_format.ToLowerInvariant())
            {
                case "csv":
                    _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV;
                    break;
                case "tsv":
                    _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV;
                    break;
                default:  // By default file format is blg
                    _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY;
                    break;
            }
        }

        private void ResolvePath()
        {
            try
            {
                Collection<PathInfo> result = null;
                result = SessionState.Path.GetResolvedPSPathFromPSPath(_path);
                if (result.Count > 1)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ExportDestPathAmbiguous"), _path);
                    Exception exc = new Exception(msg);
                    ThrowTerminatingError(new ErrorRecord(exc, "ExportDestPathAmbiguous", ErrorCategory.InvalidArgument, null));
                }

                foreach (PathInfo currentPath in result)
                {
                    _resolvedPath = currentPath.ProviderPath;
                }
            }
            catch (ItemNotFoundException pathNotFound)
            {
                //
                // This is an expected condition - we will be creating a new file
                //
                _resolvedPath = pathNotFound.ItemName;
            }
        }

        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 Exception(msg);
            if (bTerminate)
            {
                ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
            }
            else
            {
                WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null));
            }
        }
    }
}