Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 232 additions & 0 deletions Rules/AvoidUsingNewObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Language;
using System.Linq;

#if !CORECLR
using System.ComponentModel.Composition;
#endif

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif

/// <summary>
/// Rule that reports an warning when the New-Object cmdlet is used in a script.
Comment thread
iRon7 marked this conversation as resolved.
Outdated
/// The rule implements a correction that suggests using type-casting or type constructor.
///
/// Note:
/// In case a automatic correction isn't available, the rule won't report any violation either.
/// This is because if there isn't an automatic correction available, it means that the there
/// isn't a simple type-casting or type constructor that can be used as a replacement that
/// would be more efficient or has a better syntax than using New-Object.
/// In other words, if the `-ComObject` parameter is used, or both the parameters
/// `-ArgumentList` and `-Property` are used, there won't be a simple type initializer
/// available and the rule won't report any violation for the `New-Object` cmdlet.
/// </summary>
Comment thread
iRon7 marked this conversation as resolved.
public class AvoidUsingNewObject : ConfigurableRule
{

/// <summary>
/// Construct an object of AvoidUsingNewObject type.
/// </summary>
public AvoidUsingNewObject() {
Enable = false;
}

/// <summary>
/// Analyzes the given ast to find the [violation]
/// </summary>
/// <param name="ast">AST to be analyzed. This should be non-null</param>
/// <param name="fileName">Name of file that corresponds to the input AST.</param>
/// <returns>A an enumerable type containing the violations</returns>
Comment thread
iRon7 marked this conversation as resolved.
Outdated
public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure whether we want to do this this way as most other rules do have Strings.NullAstErrorMessage as argument...


IEnumerable<CommandAst> newObjectAsts = ast.FindAll(testAst =>
testAst is CommandAst cmdAst &&
cmdAst.GetCommandName() != null &&
cmdAst.GetCommandName().Equals("New-Object", StringComparison.OrdinalIgnoreCase),
true
).Cast<CommandAst>();
Comment thread
iRon7 marked this conversation as resolved.

foreach (CommandAst cmdAst in newObjectAsts)
{
// Use StaticParameterBinder to reliably get parameter values
var bindingResult = StaticParameterBinder.BindCommand(cmdAst, true);

// Check for `-TypeName` and either a `-ArgumentList` or `-Property`.
// But not both, as that would mean there isn't a simple
// type initializer available as a replacement.
if (
bindingResult.BoundParameters.Count == 2 &&
bindingResult.BoundParameters.TryGetValue("TypeName", out ParameterBindingResult asTypeName) &&
asTypeName.ConstantValue is string typeName
) {
Comment thread
iRon7 marked this conversation as resolved.
Boolean isProperty = bindingResult.BoundParameters.TryGetValue("Property", out ParameterBindingResult boundResult);
if (!isProperty)
{
Boolean isArgument = bindingResult.BoundParameters.TryGetValue("ArgumentList", out ParameterBindingResult argumentResult);
if (isArgument) { boundResult = argumentResult; } else { continue; }
}
Comment thread
iRon7 marked this conversation as resolved.

string correction = null;
if (isProperty)
{
correction = "[" + typeName + "]" + boundResult.Value.Extent.Text;
}
else if (boundResult.ConstantValue != null)
{
string valueText = boundResult.Value.Extent.Text;
if (
boundResult.Value is StringConstantExpressionAst stringConstant &&
stringConstant.StringConstantType == StringConstantType.BareWord
)
{
valueText = '"' + valueText.Replace("\"", string.Empty) + '"'; // Test""123 --> "Test123"
}
correction = "[" + typeName + "]" + valueText;
}
Comment on lines +101 to +112

@iRon7 iRon7 Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I got this right, if the -ArgumentList contains an constant value, I might use a shorter (preferred) syntax by simply casting the value expression.
For the given example: New-Object DateTime 0 vs [DateTime]0, both return the same results:

Monday, January 1, 0001 12:00:00 AM

else if (
boundResult.Value is ParenExpressionAst parenExpressionAst &&
!parenExpressionAst.Pipeline.Extent.Text.StartsWith(",")
)
Comment on lines +113 to +116

@iRon7 iRon7 Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Pipeline.Extent.Text (the inner Ast of the ParenExpressionAst) is already trimmed.
Btw. I don't think there is an easier way to check for a wrapped object (unary comma operator).

{
correction = "[" +typeName + "]::new" + parenExpressionAst.Extent.Text;
}
else if (
boundResult.Value is ArrayExpressionAst arrayExpressionAst &&
!arrayExpressionAst.SubExpression.Extent.Text.StartsWith(",")
)
{
correction = "[" + typeName + "]::new(" + arrayExpressionAst.SubExpression.Extent.Text + ")";
}
else if (
boundResult.Value is SubExpressionAst subExpressionAst &&
!subExpressionAst.SubExpression.Extent.Text.StartsWith(",")
)
{
correction = "[" + typeName + "]::new(" + subExpressionAst.SubExpression.Extent.Text + ")";
}
else if (boundResult.Value is VariableExpressionAst)
{
// correction == $null

// The correction is inconclusive, as we can't be sure if the variable contains
// a single value that can be used in a type initializer,
// or if it contains multiple values that would require splatting,
// which can't be automatically determined from the AST.
}
else
{
correction = "[" + typeName + "]::new(" + boundResult.Value.Extent.Text + ")";
}

DiagnosticRecord diagnosticRecord = new DiagnosticRecord(
string.Format(
CultureInfo.CurrentCulture,
Strings.AvoidUsingNewObjectError,
typeName
),
cmdAst.Extent,
GetName(),
DiagnosticSeverity.Warning,
fileName,
typeName
);

if (correction != null)
{
diagnosticRecord.SuggestedCorrections = new List<CorrectionExtent> {
new CorrectionExtent(
cmdAst.Extent.StartLineNumber,
cmdAst.Extent.EndLineNumber,
cmdAst.Extent.StartColumnNumber,
cmdAst.Extent.EndColumnNumber,
correction,
fileName,
string.Format(
CultureInfo.CurrentCulture,
Strings.AvoidUsingNewObjectCorrectionDescription,
typeName
)
)
};
}

yield return diagnosticRecord;
}
}
}

/// <summary>
/// Retrieves the common name of this rule.
/// </summary>
public override string GetCommonName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingNewObjectCommonName);
}

/// <summary>
/// Retrieves the description of this rule.
/// </summary>
public override string GetDescription()
{
return string.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingNewObjectDescription);
}

/// <summary>
/// Retrieves the name of this rule.
/// </summary>
public override string GetName()
{
return string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.AvoidUsingNewObjectName);
}

/// <summary>
/// Retrieves the severity of the rule: error, warning or information.
/// </summary>
public override RuleSeverity GetSeverity()
{
return RuleSeverity.Warning;
}

/// <summary>
/// Gets the severity of the returned diagnostic record: error, warning, or information.
/// </summary>
/// <returns></returns>
public DiagnosticSeverity GetDiagnosticSeverity()
{
return DiagnosticSeverity.Warning;
}

/// <summary>
/// Retrieves the name of the module/assembly the rule is from.
/// </summary>
public override string GetSourceName()
{
return string.Format(CultureInfo.CurrentCulture, Strings.SourceName);
}

/// <summary>
/// Retrieves the type of the rule, Builtin, Managed or Module.
/// </summary>
public override SourceType GetSourceType()
{
return SourceType.Builtin;
}
}
}

15 changes: 15 additions & 0 deletions Rules/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,21 @@
<data name="AvoidUsingConsoleWriteError" xml:space="preserve">
<value>File '{0}' uses Console.'{1}'. Using Console to write is not recommended because it may not work in all hosts or there may even be no hosts at all. Use Write-Output instead.</value>
</data>
<data name="AvoidUsingNewObjectCommonName" xml:space="preserve">
<value>Avoid Using New-Object</value>
</data>
<data name="AvoidUsingNewObjectDescription" xml:space="preserve">
<value>Avoid using the 'New-Object' cmdlet to create objects as it might perform poorly.</value>
</data>
<data name="AvoidUsingNewObjectName" xml:space="preserve">
<value>AvoidUsingNewObject</value>
</data>
<data name="AvoidUsingNewObjectError" xml:space="preserve">
<value>Avoid using the 'New-Object' cmdlet to create objects of type '{0}' as it might perform poorly.</value>
</data>
<data name="AvoidUsingNewObjectCorrectionDescription" xml:space="preserve">
<value>Use the type initializer '[{0}]' to construct or cast the intended object.</value>
</data>
<data name="AvoidUsingWriteHostDescription" xml:space="preserve">
<value>Avoid using the Write-Host cmdlet. Instead, use Write-Output, Write-Verbose, or Write-Information. Because Write-Host is host-specific, its implementation might vary unpredictably. Also, prior to PowerShell 5.0, Write-Host did not write to a stream, so users cannot suppress it, capture its value, or redirect it.</value>
</data>
Expand Down
Loading