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):

  1. $result = Invoke-Expression “[$type]`$value”
  2. 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.


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.


Kirk out.

Share this post:


2 thoughts on “PowerShell Challenge: Converting objects to types defined at runtime

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s