-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathInvokeScriptAnalyzerCommand.cs
537 lines (484 loc) · 19.7 KB
/
InvokeScriptAnalyzerCommand.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands
{
using PSSASettings = Microsoft.Windows.PowerShell.ScriptAnalyzer.Settings;
/// <summary>
/// InvokeScriptAnalyzerCommand: Cmdlet to statically check PowerShell scripts.
/// </summary>
[Cmdlet(VerbsLifecycle.Invoke,
"ScriptAnalyzer",
DefaultParameterSetName = ParameterSet_Path_SuppressedOnly,
SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=525914")]
[OutputType(typeof(DiagnosticRecord), typeof(SuppressedRecord))]
public class InvokeScriptAnalyzerCommand : PSCmdlet, IOutputWriter
{
private const string ParameterSet_Path_SuppressedOnly = nameof(Path) + "_" + nameof(SuppressedOnly);
private const string ParameterSet_Path_IncludeSuppressed = nameof(Path) + "_" + nameof(IncludeSuppressed);
private const string ParameterSet_ScriptDefinition_SuppressedOnly = nameof(ScriptDefinition) + "_" + nameof(SuppressedOnly);
private const string ParameterSet_ScriptDefinition_IncludeSuppressed = nameof(ScriptDefinition) + "_" + nameof(IncludeSuppressed);
#region Private variables
List<string> processedPaths;
#endregion // Private variables
#region Parameters
/// <summary>
/// Path: The path to the file or folder to invoke PSScriptAnalyzer on.
/// </summary>
[Parameter(Position = 0,
ParameterSetName = ParameterSet_Path_IncludeSuppressed,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[Parameter(Position = 0,
ParameterSetName = ParameterSet_Path_SuppressedOnly,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNull]
[Alias("PSPath")]
public string Path
{
get { return path; }
set { path = value; }
}
private string path = ".";
/// <summary>
/// ScriptDefinition: a script definition in the form of a string to run rules on.
/// </summary>
[Parameter(Position = 0,
ParameterSetName = ParameterSet_ScriptDefinition_IncludeSuppressed,
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[Parameter(Position = 0,
ParameterSetName = ParameterSet_ScriptDefinition_SuppressedOnly,
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNull]
public string ScriptDefinition
{
get { return scriptDefinition; }
set { scriptDefinition = value; }
}
private string scriptDefinition;
/// <summary>
/// CustomRulePath: The path to the file containing custom rules to run.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("CustomizedRulePath")]
public string[] CustomRulePath
{
get { return customRulePath; }
set { customRulePath = value; }
}
private string[] customRulePath;
/// <summary>
/// RecurseCustomRulePath: Find rules within subfolders under the path
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter RecurseCustomRulePath
{
get { return recurseCustomRulePath; }
set { recurseCustomRulePath = value; }
}
private bool recurseCustomRulePath;
/// <summary>
/// IncludeDefaultRules: Invoke default rules along with Custom rules
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter IncludeDefaultRules
{
get { return includeDefaultRules; }
set { includeDefaultRules = value; }
}
private bool includeDefaultRules;
/// <summary>
/// ExcludeRule: Array of names of rules to be disabled.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ExcludeRule
{
get { return excludeRule; }
set { excludeRule = value; }
}
private string[] excludeRule;
/// <summary>
/// IncludeRule: Array of names of rules to be enabled.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] IncludeRule
{
get { return includeRule; }
set { includeRule = value; }
}
private string[] includeRule;
/// <summary>
/// IncludeRule: Array of the severity types to be enabled.
/// </summary>
[ValidateSet("Warning", "Error", "Information", "ParseError", IgnoreCase = true)]
[Parameter(Mandatory = false)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Severity
{
get { return severity; }
set { severity = value; }
}
private string[] severity;
// TODO: This should be only in the Path parameter sets, and is ignored otherwise,
// but we already have a test that depends on it being otherwise
//[Parameter(ParameterSetName = ParameterSet_Path_IncludeSuppressed)]
//[Parameter(ParameterSetName = ParameterSet_Path_SuppressedOnly)]
//
/// <summary>
/// Recurse: Apply to all files within subfolders under the path
/// </summary>
[Parameter]
public SwitchParameter Recurse
{
get { return recurse; }
set { recurse = value; }
}
private bool recurse;
/// <summary>
/// ShowSuppressed: Show the suppressed message
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Path_SuppressedOnly)]
[Parameter(ParameterSetName = ParameterSet_ScriptDefinition_SuppressedOnly)]
public SwitchParameter SuppressedOnly { get; set; }
/// <summary>
/// Include suppressed diagnostics in the output.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Path_IncludeSuppressed, Mandatory = true)]
[Parameter(ParameterSetName = ParameterSet_ScriptDefinition_IncludeSuppressed, Mandatory = true)]
public SwitchParameter IncludeSuppressed { get; set; }
/// <summary>
/// Resolves rule violations automatically where possible.
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = ParameterSet_Path_IncludeSuppressed)]
[Parameter(Mandatory = false, ParameterSetName = ParameterSet_Path_SuppressedOnly)]
public SwitchParameter Fix
{
get { return fix; }
set { fix = value; }
}
private bool fix;
/// <summary>
/// Sets the exit code to the number of warnings for usage in CI.
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter EnableExit
{
get { return enableExit; }
set { enableExit = value; }
}
private bool enableExit;
/// <summary>
/// Returns path to the file that contains user profile or hash table for ScriptAnalyzer
/// </summary>
[Alias("Profile")]
[Parameter(Mandatory = false)]
[ValidateNotNull]
public object Settings
{
get { return settings; }
set { settings = value; }
}
private object settings;
private bool stopProcessing;
#if !PSV3
/// <summary>
/// Resolve DSC resource dependency
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter SaveDscDependency
{
get { return saveDscDependency; }
set { saveDscDependency = value; }
}
private bool saveDscDependency;
#endif // !PSV3
#if DEBUG
/// <summary>
/// Attaches to an instance of a .Net debugger
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter AttachAndDebug
{
get { return attachAndDebug; }
set { attachAndDebug = value; }
}
private bool attachAndDebug = false;
#endif
/// <summary>
/// Write a summary of rule violations to the host, which might be undesirable in some cases, therefore this switch is optional.
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter ReportSummary
{
get { return reportSummary; }
set { reportSummary = value; }
}
private SwitchParameter reportSummary;
#endregion Parameters
#region Overrides
/// <summary>
/// Imports all known rules and loggers.
/// </summary>
protected override void BeginProcessing()
{
// Initialize helper
#if DEBUG
if (attachAndDebug)
{
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
else
{
System.Diagnostics.Debugger.Launch();
}
}
#endif
Helper.Instance = new Helper(
SessionState.InvokeCommand,
this);
Helper.Instance.Initialize();
var psVersionTable = this.SessionState.PSVariable.GetValue("PSVersionTable") as Hashtable;
if (psVersionTable != null)
{
Helper.Instance.SetPSVersionTable(psVersionTable);
}
string[] rulePaths = Helper.ProcessCustomRulePaths(
customRulePath,
this.SessionState,
recurseCustomRulePath);
if (IsFileParameterSet() && Path != null)
{
// just used to obtain the directory to use to find settings below
ProcessPath();
}
string[] combRulePaths = null;
var combRecurseCustomRulePath = RecurseCustomRulePath.IsPresent;
var combIncludeDefaultRules = IncludeDefaultRules.IsPresent;
try
{
var settingsObj = PSSASettings.Create(
settings,
processedPaths == null || processedPaths.Count == 0 ? CurrentProviderLocation("FileSystem").ProviderPath : processedPaths[0],
this,
GetResolvedProviderPathFromPSPath);
if (settingsObj != null)
{
ScriptAnalyzer.Instance.UpdateSettings(settingsObj);
// For includeDefaultRules and RecurseCustomRulePath we override the value in the settings file by
// command line argument.
combRecurseCustomRulePath = OverrideSwitchParam(
settingsObj.RecurseCustomRulePath,
"RecurseCustomRulePath");
combIncludeDefaultRules = OverrideSwitchParam(
settingsObj.IncludeDefaultRules,
"IncludeDefaultRules");
}
// Ideally we should not allow the parameter to be set from settings and command line
// simultaneously. But since, this was done before with IncludeRules, ExcludeRules and Severity,
// we use the same strategy for CustomRulePath. So, we take the union of CustomRulePath provided in
// the settings file and if provided on command line.
var settingsCustomRulePath = Helper.ProcessCustomRulePaths(
settingsObj?.CustomRulePath?.ToArray(),
this.SessionState,
combRecurseCustomRulePath);
combRulePaths = rulePaths == null
? settingsCustomRulePath
: settingsCustomRulePath == null
? rulePaths
: rulePaths.Concat(settingsCustomRulePath).ToArray();
}
catch (Exception exception)
{
this.ThrowTerminatingError(new ErrorRecord(
exception,
"SETTINGS_ERROR",
ErrorCategory.InvalidData,
this.settings));
}
SuppressionPreference suppressionPreference = SuppressedOnly
? SuppressionPreference.SuppressedOnly
: IncludeSuppressed
? SuppressionPreference.Include
: SuppressionPreference.Omit;
ScriptAnalyzer.Instance.Initialize(
this,
combRulePaths,
this.includeRule,
this.excludeRule,
this.severity,
combRulePaths == null || combIncludeDefaultRules,
suppressionPreference);
}
/// <summary>
/// Analyzes the given script/directory.
/// </summary>
protected override void ProcessRecord()
{
if (stopProcessing)
{
stopProcessing = false;
return;
}
if (IsFileParameterSet())
{
ProcessPath();
}
#if !PSV3
// TODO Support dependency resolution for analyzing script definitions
if (saveDscDependency)
{
using (var rsp = RunspaceFactory.CreateRunspace())
{
rsp.Open();
using (var moduleHandler = new ModuleDependencyHandler(rsp))
{
ScriptAnalyzer.Instance.ModuleHandler = moduleHandler;
this.WriteVerbose(
String.Format(
CultureInfo.CurrentCulture,
Strings.ModuleDepHandlerTempLocation,
moduleHandler.TempModulePath));
ProcessInput();
}
}
return;
}
#endif
ProcessInput();
}
protected override void EndProcessing()
{
ScriptAnalyzer.Instance.CleanUp();
base.EndProcessing();
}
protected override void StopProcessing()
{
ScriptAnalyzer.Instance.CleanUp();
base.StopProcessing();
}
#endregion
#region Private Methods
private void ProcessInput()
{
WriteToOutput(RunAnalysis());
}
private IEnumerable<DiagnosticRecord> RunAnalysis()
{
if (!IsFileParameterSet())
{
return ScriptAnalyzer.Instance.AnalyzeScriptDefinition(scriptDefinition, out _, out _);
}
var diagnostics = new List<DiagnosticRecord>();
foreach (string path in this.processedPaths)
{
if (fix)
{
ShouldProcess(path, $"Analyzing and fixing path with Recurse={this.recurse}");
diagnostics.AddRange(ScriptAnalyzer.Instance.AnalyzeAndFixPath(path, this.ShouldProcess, this.recurse));
}
else
{
ShouldProcess(path, $"Analyzing path with Recurse={this.recurse}");
diagnostics.AddRange(ScriptAnalyzer.Instance.AnalyzePath(path, this.ShouldProcess, this.recurse));
}
}
return diagnostics;
}
private void WriteToOutput(IEnumerable<DiagnosticRecord> diagnosticRecords)
{
foreach (ILogger logger in ScriptAnalyzer.Instance.Loggers)
{
var errorCount = 0;
var warningCount = 0;
var infoCount = 0;
var parseErrorCount = 0;
foreach (DiagnosticRecord diagnostic in diagnosticRecords)
{
logger.LogObject(diagnostic, this);
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Information:
infoCount++;
break;
case DiagnosticSeverity.Warning:
warningCount++;
break;
case DiagnosticSeverity.Error:
errorCount++;
break;
case DiagnosticSeverity.ParseError:
parseErrorCount++;
break;
default:
throw new ArgumentOutOfRangeException(nameof(diagnostic.Severity), $"Severity '{diagnostic.Severity}' is unknown");
}
}
if (ReportSummary.IsPresent)
{
var numberOfRuleViolations = infoCount + warningCount + errorCount;
if (numberOfRuleViolations == 0)
{
Host.UI.WriteLine("0 rule violations found.");
}
else
{
var pluralS = numberOfRuleViolations > 1 ? "s" : string.Empty;
var message = $"{numberOfRuleViolations} rule violation{pluralS} found. Severity distribution: {DiagnosticSeverity.Error} = {errorCount}, {DiagnosticSeverity.Warning} = {warningCount}, {DiagnosticSeverity.Information} = {infoCount}";
if (warningCount + errorCount == 0)
{
ConsoleHostHelper.DisplayMessageUsingSystemProperties(Host, "WarningForegroundColor", "WarningBackgroundColor", message);
}
else
{
ConsoleHostHelper.DisplayMessageUsingSystemProperties(Host, "ErrorForegroundColor", "ErrorBackgroundColor", message);
}
}
}
}
if (EnableExit.IsPresent)
{
this.Host.SetShouldExit(diagnosticRecords.Count());
}
}
private void ProcessPath()
{
Collection<PathInfo> paths = this.SessionState.Path.GetResolvedPSPathFromPSPath(path);
processedPaths = new List<string>();
foreach (PathInfo p in paths)
{
processedPaths.Add(this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(p.Path));
}
}
private bool IsFileParameterSet() => Path is not null;
private bool OverrideSwitchParam(bool paramValue, string paramName)
{
return MyInvocation.BoundParameters.ContainsKey(paramName)
? ((SwitchParameter)MyInvocation.BoundParameters[paramName]).ToBool()
: paramValue;
}
#endregion // Private Methods
}
}