PowerShell Creating Objects


The New-Object cmdlet is used to create an object.

# Create a DateTime object and stores the object in variable "$var"
$var = New-Object System.DateTime

# calling constructor with parameters
$sr = New-Object System.IO.StreamReader -ArgumentList "file path"

In many instances, a new object will be created in order to export data or pass it to another commandlet. This can be done like so:

$newObject = New-Object -TypeName PSObject -Property @{
    ComputerName = "SERVER1"
    Role = "Interface"
    Environment = "Production"

There are many ways of creating an object. The following method is probably the shortest and fastest way to create a PSCustomObject:

$newObject = [PSCustomObject]@{
    ComputerName = 'SERVER1'
    Role         = 'Interface'
    Environment  = 'Production'

In case you already have an object, but you only need one or two extra properties, you can simply add that property by using Select-Object:

Get-ChildItem | Select-Object FullName, Name, 
    @{Name='DateTime'; Expression={Get-Date}}, 
    @{Name='PropertieName'; Expression={'CustomValue'}}

All objects can be stored in variables or passed into the pipeline. You could also add these objects to a collection and then show the results at the end.

Collections of objects work well with Export-CSV (and Import-CSV). Each line of the CSV is an object, each column a property.

Format commands convert objects into text stream for display. Avoid using Format-* commands until the final step of any data processing, to maintain the usability of the objects.