我可以使用数组 属性 创建自定义 PowerShell 对象吗?
Can I create a custom PowerShell object with an array property?
警告:我希望在 PowerShell v2 中执行此操作(抱歉!)。
我想要一个具有数组 属性 的自定义对象(可能创建为自定义类型)。我知道如何制作具有 "noteproperty" 属性的自定义对象:
$person = new-object PSObject
$person | add-member -type NoteProperty -Name First -Value "Joe"
$person | add-member -type NoteProperty -Name Last -Value "Schmoe"
$person | add-member -type NoteProperty -Name Phone -Value "555-5555"
并且我知道如何从自定义类型创建自定义对象:
Add-Type @"
public struct PersonType {
public string First;
public string Last;
public string Phone;
}
"@
$person += New-Object PersonType -Property @{
First = "Joe";
Last = "Schmoe";
Phone = "555-5555";
}
如何创建类型包含数组 属性 的自定义对象?像这样的散列 table,但作为一个对象:
$hash = @{
First = "Joe"
Last = "Schmoe"
Pets = @("Fluffy","Spot","Stinky")
}
我很确定我可以在 PowerShell v3 中使用 [PSCustomObject]$hash
来做到这一点,但我需要包含 v2。
谢谢。
当你使用Add-Member
添加你的笔记属性时,-Value
可以是一个数组。
$person | add-member -type NoteProperty -Name Pets -Value @("Fluffy","Spot","Stinky")
如果您想首先将属性创建为哈希表,就像您的示例一样,您也可以将其传递给 New-Object
:
$hash = @{
First = "Joe"
Last = "Schmoe"
Pets = @("Fluffy","Spot","Stinky")
}
New-Object PSObject -Property $hash
您的 PersonType
示例实际上是用 C# 编写的,作为一个动态编译的字符串,因此语法将是数组的 C# 语法 属性:
Add-Type @"
public struct PersonType {
public string First;
public string Last;
public string Phone;
public string[] Pets;
}
"@
警告:我希望在 PowerShell v2 中执行此操作(抱歉!)。
我想要一个具有数组 属性 的自定义对象(可能创建为自定义类型)。我知道如何制作具有 "noteproperty" 属性的自定义对象:
$person = new-object PSObject
$person | add-member -type NoteProperty -Name First -Value "Joe"
$person | add-member -type NoteProperty -Name Last -Value "Schmoe"
$person | add-member -type NoteProperty -Name Phone -Value "555-5555"
并且我知道如何从自定义类型创建自定义对象:
Add-Type @"
public struct PersonType {
public string First;
public string Last;
public string Phone;
}
"@
$person += New-Object PersonType -Property @{
First = "Joe";
Last = "Schmoe";
Phone = "555-5555";
}
如何创建类型包含数组 属性 的自定义对象?像这样的散列 table,但作为一个对象:
$hash = @{
First = "Joe"
Last = "Schmoe"
Pets = @("Fluffy","Spot","Stinky")
}
我很确定我可以在 PowerShell v3 中使用 [PSCustomObject]$hash
来做到这一点,但我需要包含 v2。
谢谢。
当你使用Add-Member
添加你的笔记属性时,-Value
可以是一个数组。
$person | add-member -type NoteProperty -Name Pets -Value @("Fluffy","Spot","Stinky")
如果您想首先将属性创建为哈希表,就像您的示例一样,您也可以将其传递给 New-Object
:
$hash = @{
First = "Joe"
Last = "Schmoe"
Pets = @("Fluffy","Spot","Stinky")
}
New-Object PSObject -Property $hash
您的 PersonType
示例实际上是用 C# 编写的,作为一个动态编译的字符串,因此语法将是数组的 C# 语法 属性:
Add-Type @"
public struct PersonType {
public string First;
public string Last;
public string Phone;
public string[] Pets;
}
"@