创建自定义 PSObject PowerShell 2.0 [英] Create Custom PSObject PowerShell 2.0
问题描述
是否可以创建自定义对象 (PSObject) 并在程序执行之前和之后定义其属性,我们会不断向对象添加值数组.
Is it possible to create a Custom Object (PSObject) and define its properties beforehand and later in the program execution, we keep adding array of values to the object.
例如;
$c = @()
$c = New-Object PSObject
$c | Add-Member -type NoteProperty -name Name
$c | Add-Member -type NoteProperty -name Gender
$c | Add-Member -type NoteProperty -name Age
$c | Add-Member -type NoteProperty -name Name -value "John"
$c | Add-Member -type NoteProperty -name Gender -value "Male"
$c | Add-Member -type NoteProperty -name Age -value "30"
提前感谢您提供任何线索或建议.
Thanks in advance for any leads or advice.
推荐答案
我不确定我是否遵循.您是否需要具有指定属性的对象数组?因为您的示例首先创建一个数组,然后您将其覆盖为单个对象.所以你失去了你的阵列.
I'm not sure I follow. Do you want an array of objects with your specified properties? Because your sample first creates an array, that you then overwrite into a single object. So you lost your array.
您可以使用 new-object
创建对象,并在 -Property
参数中将属性值指定为哈希表.像这样:
You can create the object using new-object
and specify the properties with values as a hashtable in the -Property
parameter. Like this:
$c = New-Object psobject -Property @{
Name = "John"
Gender = "Male"
Age = 30
}
要制作它们的数组,您可以使用:
To make an array of them, you can use:
$myarray = @()
$myarray += New-Object psobject -Property @{
Name = "John"
Gender = "Male"
Age = 30
}
如果你有多个测试一个一个运行,你可以在一个测试并创建一个resultobject"的函数中运行这些测试,然后你收集它:
If you have multiple tests that you run one by one, you can run the tests in a function that tests and creates a "resultobject", then you collect it:
$myresults = @()
function mytests($computer) {
#Test connection
$online = Test-Connection $computer
#Get buildnumber
$build = (Get-WmiObject win32_operatingsystem -ComputerName $computer).buildnumber
#other tests
#output results
New-Object psobject -Property @{
Online = $online
WinBuild = $build
}
}
$myresults += mytests -computer "mycomputername"
这篇关于创建自定义 PSObject PowerShell 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!