PowerShell Cmdlet Deep Dive: New-Object
Welcome back to Wahmans PowerShell blog! Today we’re going to take a closer look at one of the foundational cmdlets in PowerShell: New-Object.
The official Microsoft description says:
New-Object: Creates an instance of a Microsoft .NET Framework or COM object.
In other words, New-Object gives you the power to create and work with .NET and COM objects directly from your PowerShell scripts. This can be incredibly useful for building rich tools, accessing system information, or integrating with legacy systems.
When to use New-Object
While recent versions of PowerShell encourage method-based object creation like [type]::new(), New-Object remains important for interacting with older systems, COM objects, or scripts for cross-version compatibility.
Example 1: Creating a simple .NET object (Beginner)
Let’s start small and create a basic .NET object using New-Object.
# Create a DateTime object
date = New-Object System.DateTime(2024, 1, 1)
Write-Output $date
This will create a new DateTime object representing January 1st, 2024.
Example 2: Using New-Object with -Property to create a custom object (Intermediate)
You can combine New-Object with -Property to create simple custom objects on the fly.
$user = New-Object PSObject -Property @{
FirstName = "Jane"
LastName = "Doe"
Age = 29
}
Write-Output $user
This is great for building data structures quickly without formally defining a class.
Example 3: Creating a COM object for Excel automation (Advanced)
Let’s see how New-Object can create a COM object to automate Excel.
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Add()
$sheet = $workbook.Sheets.Item(1)
$sheet.Cells.Item(1,1).Value = "Hello, Excel!"
# Don't forget to clean up
$excel.Quit()
COM objects are powerful but require careful handling and cleanup to avoid leaving processes running.
Example 4: Creating objects with constructors (Advanced)
For some .NET types, you can pass arguments directly to the constructor via New-Object.
# Create a TCPClient to connect to a host
$client = New-Object System.Net.Sockets.TcpClient("www.example.com", 80)
if ($client.Connected) {
Write-Output "Connected to www.example.com on port 80"
}
$client.Close()
This is useful for advanced network scripting and more complex automation tasks.
Conclusion
New-Object is versatile, time-tested, and still very relevant in modern PowerShell scripts. From creating simple data structures to interfacing with COM components or building sophisticated .NET functionality, this cmdlet has got you covered.
Happy scripting, and I will see you in the next post!
Leave a Reply