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.
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.
|Share this post:|