向自定义对象添加行

向自定义对象添加行

本文介绍了Powershell:向自定义对象添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.

$strProjectPath="C:\temp\mps.xls";
$strServersExtr= @()
$strOSExtr= @()
$objServersList = New-Object PSObject
$objServersList | Add-Member -MemberType NoteProperty -Name ServerName -Value "" -PassThru | Add-Member -MemberType NoteProperty -Name OSType -Value ""

我读取了一个 Excel 文件(通过循环)以将 2 个特定列放置到这两个成员中.问题是我不能一个接一个地添加值".+= 不适用于对象.我也尝试收集到和数组然后到对象,但它也不起作用.如何向已经存在的对象添加线条?

I read an Excel file (through a loop) to put 2 specific columns to these two members. The problem is that I can't add "Values" one after the other. += doesn't work with objects. I had try also to collect to and array and then to the object but it didn't work also. How is it possible to add lines to an already existing object?

示例:

ServerName                                                  OSType
----------                                                  ------
blabla1                                                     Windows XP
blabla2                                                     Windows 7 Professional

PS1.$strServersExtr 和 $strOSExtr 试图收集 2 个数组中的 2 列,然后将它们放入对象中.

PS1.The $strServersExtr and the $strOSExtr was an attempt to collect the 2 columns in the 2 arrays and then put them in to the object.

PS2.我使用 PS 3.0,但任何解决方案都会更可取,因为我试图使代码易于在 PS 2.0 上工作.

PS2. I work with PS 3.0 but any solution will be preferable as I try to make the code easy to work on PS 2.0.

推荐答案

正如我所见,您需要对象数组(不是行").所以

As I see it u want array of objects (not 'lines'). So

$serverList= @()
$serverList+= @{ServerName= 'blabla1'; OSType='Windows XP'}
$serverList+= @{ServerName= 'blabla2'; OSType='Windows XP Profesional'}

#display as table
$serverList | % { new-object PSObject -Property $_}

这篇关于Powershell:向自定义对象添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 10:29