3

I am creating a new object in a Powershell script, or actually an object type. I want to create multiple instances of this object. How do I do this?

The code below is what I am working on, it appears that all instances in the array reference the same object, containing the same values.

# Define output object
$projectType = new-object System.Object
$projectType | add-member -membertype noteproperty -value "" -name Project
$projectType | add-member -membertype noteproperty -value "" -name Category
$projectType | add-member -membertype noteproperty -value "" -name Description

# Import data
$data = import-csv $input -erroraction stop

# Create a generic collection object
$projects = @()

# Parse data
foreach ($line in $data) {
    $project = $projectType

    $project.Project = $line.Id
    $project.Category = $line.Naam
    $project.Description = $line.Omschrijving
    $projects += $project
}

$projects | Export-Csv output.csv -NoTypeInformation -Force

1 Answer 1

4

You have to use New-Object for any, well, new object, otherwise being a reference type $projectType in your code refers to the same object. Here is the changed code:

# Define output object
function New-Project {
    New-Object PSObject -Property @{
        Project = ''
        Category = ''
        Description = ''
    }
}

# Parse data
$projects = @()
foreach ($line in 1..9) {
    $project = New-Project
    $project.Project = $line
    $project.Category = $line
    $project.Description = $line
    $projects += $project
}

# Continue
$projects

In this particular case instead of using the function New-Project you can just move its body into the loop, e.g. $project = New-Object PSObject …. But if you create your “projects” elsewhere then having this function will be useful there as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok thats clear, how would I add a ToString function (for debugging) to the newly created object using your method?
This is not exactly ToString() you ask for but try this: $projects | % {"$_"}. You will get strings like this: @{Description=...; Category=...; Project=...}. For debugging this should be enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.