Creating objects

suggest change

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

# Create a DateTime object and store it in $var
$var = New-Object System.DateTime

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

Often you create an object so you can export data or pass it to another cmdlet:

$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='PropertyName'; 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 for display. Avoid them until the final step of any data processing, or later commands in the pipeline will see formatting records instead of the original objects.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents