Hey everyone! I've been trying to figure out how to create an array or hashtable in PowerShell with multiple properties by hand, but all the blog posts I've read make things so complicated. I really want to make it simple. For example, I know how to create a single entry with properties like this:
$x = New-Object psobject -Property @{
row1= "john"
row2 = "doe"
}
But when I try to create a variable with multiple entries, my attempts keep ending up wrong. I thought doing something like this would work:
$x = New-Object psobject -Property @{
row1= "john", "maggie"
row2 = "doe", "smith"
}
But it just gives me a single entry with arrays instead of separate entries. I want it formatted like this:
PS C:Users> $x
row1 row2
---- ----
john doe
maggie smith
Can anyone give me simple tips or keywords to search for to help me figure this out?
3 Answers
To simplify things, instead of using `New-Object`, you can make it more efficient. Here's a cool shortcut:
$YourVariableName = [PSCustomObject]@{
Property_1 = 'Value_1'
Property_2 = 'Value_2'
}
The trick is that you need an array of objects, not a single object with array properties. Like this:
$YourVariableName = @(
[PSCustomObject]@{
Property_1 = 'Value_1'
Property_2 = 'Value_2'
},
[PSCustomObject]@{
Property_1 = 'Value_1_First'
Property_2 = 'Value_2_Second'
}
)
Check this link for more details about arrays and hashtables. It's super helpful!
You can separate the entries with commas like this:
[pscustomobject]@{
row1 = "john"
row2 = "maggie"
}, [pscustomobject]@{
row1 = "doe"
row2 = "smith"
}
Alternatively, you could convert data from a structured format like CSV:
@'
row1, row2
john, maggie
doe, smith
'@ | ConvertFrom-Csv
This way works nicely if you want to keep things simple without any files involved!
Oh cool, thank you! I will steal the ConvertFrom-Csv method, because I knew that I could have done it via Import-Csv, but your method works without access to storage 😀
Sorry if this is a bit rough, but you can structure it like this:
@(
[PSCustomObject]@{
Status = "SomeValue"
Name = "SomeOtherValue"
DisplayName = "SomeAlt value"
},
[PSCustomObject]@{
Status = "SomeValue2"
Name = "SomeOtherValue2"
DisplayName = "SomeAlt value2"
}
)
No Problem and thank you! That was exactly what I meant - now I finally understood where I made an error 🙂
omg - THANK YOU. Now it finally made click in my head and I can see my error. This was exactly what I was looking for!