Skip to content

Commit 841dba6

Browse files
author
Kapil Borle
committed
Add method to check SupportShouldProcess for builtin cmdlet
1 parent a488d70 commit 841dba6

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Rules/UseShouldProcessCorrectly.cs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
using System.ComponentModel.Composition;
2020
#endif
2121
using System.Globalization;
22+
using System.Reflection;
2223

2324
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
2425
{
@@ -261,6 +262,54 @@ private bool DeclaresSupportsShouldProcess(FunctionDefinitionAst ast)
261262

262263
return false;
263264
}
265+
266+
private bool DeclaresSupportsShouldProcess(string cmdName)
267+
{
268+
if (String.IsNullOrWhiteSpace(cmdName))
269+
{
270+
return false;
271+
}
272+
273+
try
274+
{
275+
using (var ps = System.Management.Automation.PowerShell.Create())
276+
{
277+
ps.AddCommand("Get-command").AddArgument("cmdName");
278+
var cmdInfo = ps.Invoke<System.Management.Automation.CmdletInfo>().FirstOrDefault();
279+
if (cmdInfo == null)
280+
{
281+
return false;
282+
}
283+
var attributes = cmdInfo.ImplementingType.GetTypeInfo().GetCustomAttributes(
284+
typeof(System.Management.Automation.CmdletCommonMetadataAttribute),
285+
true);
286+
287+
foreach (var attr in attributes)
288+
{
289+
var cmdletAttribute = attr as System.Management.Automation.CmdletAttribute;
290+
if (cmdletAttribute == null)
291+
{
292+
continue;
293+
}
294+
295+
if (cmdletAttribute.SupportsShouldProcess)
296+
{
297+
return true;
298+
}
299+
}
300+
if (attributes.Count() == 0)
301+
{
302+
return false;
303+
}
304+
}
305+
}
306+
catch (System.Management.Automation.CommandNotFoundException e)
307+
{
308+
return false;
309+
}
310+
311+
return false;
312+
}
264313
}
265314

266315
/// <summary>
@@ -425,6 +474,17 @@ public override AstVisitAction VisitCommand(CommandAst ast)
425474
return AstVisitAction.Continue;
426475
}
427476

477+
// if command is part of a binary module
478+
// for now just check if (Get-Command <CommandName>).DLL end with dll extension
479+
// if so, check if it declares SupportsShouldProcess
480+
// if so, then assume it also calls ShouldProcess
481+
// because we do not have a way to analyze its definition
482+
// to actually verify it is indeed calling ShouddProcess
483+
484+
// if (IsPartOfBinaryModule(cmdName, out cmdInfo))
485+
// if (HasSupportShouldProcessAttribute(cmdInfo))
486+
// AddEdge(cmdName, shouldProcessVertex)
487+
428488
var vertex = new Vertex (cmdName, ast);
429489
AddVertex(vertex);
430490
if (IsWithinFunctionDefinition())

0 commit comments

Comments
 (0)