创建自定义Powershell对象的多个实例 [英] Create multiple instances of custom Powershell object

查看:83
本文介绍了创建自定义Powershell对象的多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Powershell脚本中创建一个新对象,或者实际上是一个对象类型.我想创建该对象的多个实例.我该怎么做呢?

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

推荐答案

您必须对任何 new 对象使用New-Object,否则在您的代码中使用引用类型$projectType指相同的对象.这是更改后的代码:

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

在这种特殊情况下,无需使用功能New-Project,您只需将其主体移入循环中即可,例如$project = New-Object PSObject ….但是,如果您在其他地方创建项目",那么在此功能也将很有用.

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.

这篇关于创建自定义Powershell对象的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆