Question:
Suppose I have an array of hashes in Powershell v3:
1 2 |
> $hashes = 1..5 | foreach { @{Name="Item $_"; Value=$_}} |
I can convert a single hash into a PSCustomObject
like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
> $co = [PSCustomObject] $hashes[0] > $co | ft -AutoSize Value Name ----- ---- 1 Item 1 > $co.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False PSCustomObject System.Object |
So far, so good. The problem occurs when I try to convert the entire hash array into PSCustomObjects
in a pipeline:
1 2 3 4 5 6 |
> ($hashes | foreach { [PSCustomObject] $_})[0].getType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Hashtable System.Object |
As you see, I’m getting an array of Hashtable
objects, not PSCustomObjects
. Why do I get different behavior, and how can I accomplish what I want?
Thanks.
Answer:
I have yet to figure out the exact cause (Everyone is still learning something) but your issue is related to the $_
pipe element somehow. I can make your code work if I force a cast of the $_
1 2 3 |
$hashes = 1..5 | foreach { @{Name="Item $_"; Value=$_}} $hashes | %{([pscustomobject][hashtable]$_)} |
Output
1 2 3 4 5 6 7 8 |
Value Name ----- ---- 1 Item 1 2 Item 2 3 Item 3 4 Item 4 5 Item 5 |
Something curious
I didn’t like Name
and Value
, while I was testing (That is what a literal hash table had for headers and I found it confusing while I was testing), so I changed the later to Data
and then the output differs. I only post it as it is curious. It is hard to show the results in the post.
1 2 3 4 5 6 7 8 |
Name Data ---- ---- Item 1 1 Item 2 2 Item 3 3 Item 4 4 Item 5 5 |