PowerShell Challenge: Converting objects to types defined at runtime
I was recently working on a function where I had to convert objects to a type that was passed into the function when I came across something that may surprise some people. Assuming you have a type stored in $type, what is the difference between the following two commands (other than style):
- $result = Invoke-Expression “[$type]`$value”
- Invoke-Expression “`$result = [$type]`$value”
I don’t have any prizes for this, but I thought it was worth asking just for fun. I’ll post the solution after people have had some time to take a crack at it.
Solution
It’s been long enough to let people chew on this, so I can share the solution. Only two people came back to me indicating that they had figured it out: Arnoud Jansveld and Thomas Lee.
The key difference between these is in how data is assigned to the $result variable when using an array. In the first case, Invoke-Expression returns the converted $value (after it has been case to $type), but that return $value is then implicitly sent to Out-Default, which returns generic objects (boxing), so in the end if you started with an array you have a collection of objects (System.Object[]). In the second case, the assignment is done inside of Invoke-Expression, before any boxing would occur. Once the assignment is done, nothing is returned from Invoke-Expression, and you end up with an array of the type you were expecting.
This was just a silly little exercise, but it illustrates an important concept in PowerShell by showing how objects coming out the end of a pipeline are boxed in generic System.Objects. That knowledge comes in handy from time to time when you are scripting, so it is worth remembering.
Enjoy!
Kirk out.




If the timing were better (we’re not doing a show this wek), then I’d post this on the podcast.
Interesting question – and it took typing it out in PowerShell to work out the answer.