Creating Objects with CSV

by Oct 1, 2013

There are many ways to create custom objects. Here's a creative solution that can be useful in many scenarios: create a text-based comma-separated list of values, and use ConvertFrom-Csv to produce objects:

for($x=0 $x -lt 20 $x++)
{
    ($x,(Get-Random),(Get-Date) -join ',') | ConvertFrom-Csv -Header ID, RandomNumber, Date

} 

Unfortunately, this approach isn't very fast. So here are three other techniques to create objects with content. Measure-Command measures the time it takes to create 2000 objects:

Measure-Command {
for($x=0 $x -lt 2000 $x++)
{
    ($x,(Get-Random),(Get-Date) -join ',') | ConvertFrom-Csv -Header ID, RandomNumber, Date
}
}

Measure-Command {
for($x=0 $x -lt 2000 $x++)
{
    $obj = 1 | Select-Object -Property ID, RandomNumber, Date
    $obj.ID = $x
    $obj.RandomNumber = Get-Random
    $obj.Date = Get-Date
    $obj
}
}

Measure-Command {
for($x=0 $x -lt 2000 $x++)
{
    [PSObject]@{
        ID = $x
        RandomNumber = Get-Random
        Date = Get-Date
    }
}
}

Measure-Command {
for($x=0 $x -lt 2000 $x++)
{
    [Ordered]@{
        ID = $x
        RandomNumber = Get-Random
        Date = Get-Date
    }
}
}


As it turns out, the last two approaches are about 3 times faster than the CSV approach, yet all of these take significantly less than 1 second on our test system, so the real world differences are not of practical significance.

Pick the one you personally like best – but note that the last example needs PowerShell 3.0 or better.

Twitter This Tip! ReTweet this Tip!