我能否创建一个包含数组属性的自定义PowerShell对象?

3

警告:我想在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";
    }

我该如何创建一个自定义对象,其中类型包括数组属性?就像这个哈希表一样,但是作为一个对象:

$hash = @{
    First = "Joe"
    Last  = "Schmoe"
    Pets  = @("Fluffy","Spot","Stinky")
}

我相信我可以使用PowerShell v3中的 $hash来实现这一点,但我需要包括v2。
谢谢。

1
New-Object PSObject -Property $hash - user4003407
限制自己使用v2的原因是什么? - Maximilian Burszley
1个回答

3
当您使用 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;
  }
"@

太好了!谢谢!(我发誓我之前尝试过哈希表选项,但是现在可以工作了!) - Teknowledgist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接