Creating Multiple Instances of a Custom Powershell Object

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 should I do it?

Below is the code I'm working on, it seems that all instances of the array refer to 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
+3
source share
1 answer

You must use New-Objectfor any, well, new object, otherwise this reference type $projectTypein your code refers to the same object. Here is the modified 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

New-Project , . $project = New-Object PSObject …. "" , .

+4

Source: https://habr.com/ru/post/1745988/


All Articles