gpt4 book ai didi

arrays - 我可以创建具有数组属性的自定义 PowerShell 对象吗?

转载 作者:行者123 更新时间:2023-12-04 22:25:31 25 4
gpt4 key购买 nike

警告:我希望在 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 中使用 [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;
}
"@

关于arrays - 我可以创建具有数组属性的自定义 PowerShell 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51620654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com