New Object - PowerShell


Overview

New-Object is a foundational PowerShell command used to instantiate objects from a specified type or class definition. It enables the creation of new objects in memory, which can represent entities from the operating system, applications, and even custom objects defined in scripts or modules.

Syntax

New-Object [[-TypeName] <String>] [-ArgumentList <Object[]>]
           [-Type <Type>] [-ExcludeProperties <PropertySet>]
           [-IncludeProperties <PropertySet>] [-InitializationScriptBlock <ScriptBlock>]
           [-MemberSet <Object>] [-Property <String, Object>] [-PassThru]
           [-ReferenceType] [-SessionState]
           [-Parameter <ParameterDeclaration>]
           [-ErrorAction <ActionPreference>] [-ErrorVariable <String>]
           [-OutBuffer <Int32>] [-OutVariable <String>]
           [-Verbose] [-Debug] [-WhatIf] [-Confirm]

Options/Flags

-TypeName: Specifies the full name of the type or class to instantiate.

-Type: Alias for -TypeName.

-ArgumentList: Array of arguments to pass to the type or class constructor.

-InitializationScriptBlock: ScriptBlock to execute after the object is created.

-MemberSet: Object containing properties to set on the new object.

-Property: Name-value pair to set on the new object.

-PassThru: Returns the newly created object.

-ReferenceType: Creates a reference-type object even if the specified type is a value type.

-SessionState: Creates the object in the specified session state.

-Parameter: Declares a parameter for the object’s constructor.

Examples

Create a new System.String object:

$name = New-Object System.String "John Doe"

Create a new System.Array object with an ArgumentList:

$numbers = New-Object System.Array -ArgumentList (1, 2, 3, 4)

Customize object properties using -MemberSet:

$computer = New-Object -TypeName PSObject -MemberSet @{
  Name = "Server1"
  Status = "Online"
}

Common Issues

  • Type resolution failure: Ensure that the specified -TypeName is valid and fully qualified.
  • Constructor argument mismatch: Check that the number and types of arguments match the constructor requirements.
  • Serialization issues: When creating objects from serialized data, such as XML, ensure that the data is properly formatted and matches the expected object structure.

Integration

New-Object can be used in conjunction with various other PowerShell commands for complex tasks:

  • ConvertTo-Json to serialize created objects into JSON format.
  • Where-Object to filter a collection of objects based on criteria.
  • Invoke-Command to create objects on remote systems.
  • New-Item
  • New-Variable
  • Get-Type