How can I generate an array of PSCustomObjects from an array of hashes in Powershell v3?

Question:

Suppose I have an array of hashes in Powershell v3:

I can convert a single hash into a PSCustomObject like this:

So far, so good. The problem occurs when I try to convert the entire hash array into PSCustomObjects in a pipeline:

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 $_

Output

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.

Source:

How can I generate an array of PSCustomObjects from an array of hashes in Powershell v3? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply