@@ -4,13 +4,11 @@ ms.date: 06/06/2026
44ms.topic : reference
55title : AvoidUsingNewObject
66---
7- <!-- markdownlint-disable MD025 -->
87# AvoidUsingNewObject
9- <!-- markdownlint-enable MD025 -->
108
11- <!-- markdownlint-disable MD036 -->
129** Severity Level: Warning**
13- <!-- markdownlint-enable MD036 -->
10+
11+ ** Default state: Disabled**
1412
1513## Description
1614
@@ -19,15 +17,27 @@ Instead, use a type initializer to construct or cast the intended object.
1917
2018## Example
2119
22- ### Wrong
20+ ### Noncompliant
2321
2422``` powershell
2523# Create a version object using New-Object
2624$Version = New-Object -TypeName Version -ArgumentList "1.2.3"
2725```
2826
27+ ### Compliant
28+
29+ ``` powershell
30+ # Create a version object using the type constructor
31+ $Version = [Version]"1.2.3"
32+ ```
33+
34+ ## Examples
35+
36+ ### Creating multiple Custom Objects
37+
38+ #### Noncompliant
39+
2940``` powershell
30- # Create a custom object using New-Object
3141for ($i = 0; $i -lt 100000; $i++) {
3242 $resultObject = New-Object PSCustomObject -Property @{
3343 Name = "Name$i"
@@ -36,19 +46,9 @@ for ($i = 0; $i -lt 100000; $i++) {
3646}
3747```
3848
39- ``` powershell
40- $hashSet = New-Object -TypeName 'System.Collections.Generic.HashSet[String]' -ArgumentList ([StringComparer]::InvariantCultureIgnoreCase)
41- ```
42-
43- ### Correct
49+ #### Compliant
4450
4551``` powershell
46- # Create a version object using the type constructor
47- $Version = [Version]"1.2.3"
48- ```
49-
50- ``` powershell
51- # Create a custom object using a hashtable and type-casting
5252for ($i = 0; $i -lt 100000; $i++) {
5353 $resultObject = [PSCustomObject]@{
5454 Name = "Name$i"
@@ -57,11 +57,24 @@ for ($i = 0; $i -lt 100000; $i++) {
5757}
5858```
5959
60+ ### Creating a case-insensitive HashSet
61+
62+ #### Noncompliant
63+
6064``` powershell
61- $hashSet = [System.Collections.Generic.HashSet[String]]::new([StringComparer]::InvariantCultureIgnoreCase)
65+ $hashSet = New-Object -TypeName 'System.Collections.Generic.HashSet[String]' -ArgumentList ([StringComparer]::InvariantCultureIgnoreCase)
66+ ```
67+
68+ #### Compliant
69+
70+ ``` powershell
71+ $hashSet = [System.Collections.Generic.HashSet[String]]::new([StringComparer]:::InvariantCultureIgnoreCase)
6272```
6373
64- ## Configuration
74+ ## Configure rule
75+
76+ This rule is disabled by default, but can be enabled by adding the following
77+ configuration to your ` PSScriptAnalyzerSettings.psd1 ` file:
6578
6679``` powershell
6780Rules = @{
@@ -71,7 +84,7 @@ Rules = @{
7184}
7285```
7386
74- ### Parameters
87+ ## Parameters
7588
7689- ` Enable ` : ** bool** (Default value is ` $false ` )
7790
0 commit comments