Understanding PowerShell’s Type Conversion Magic
Type Conversion in PowerShell is, without question, one of the most useful ingredients in its "Magic Sauce" of administrator effectiveness. When you run a command with a specific parameter type (I.e.: a DateTime or a TimeSpan), things seem to "just work".
For example, consider this recent question / info dump on Twitter:
#PowerShell parameters that take a timespan object interpret 10 as 10 ticks, 10:00 as 10 hours, and "10" as 10 days.
— June Blender (@juneb_get_help) June 6, 2013
Here are the steps that PowerShell takes on your behalf to convert input to a given type – such as TimeSpan. As with many things, there is no magic – just a lot of hard work.
- Direct assignment. If your input is directly assignable, simply cast your input to that type.
- Language-based conversion. These language-based conversions are done when the target type is void, Boolean, String, Array, Hashtable, PSReference (i.e.: [ref]), XmlDocument (i.e.: [xml]). Delegate (to support ScriptBlock to Delegate conversions), and Enum.
- Parse conversion. If the target type defines a Parse() method that takes that input, use that.
- Static Create conversion. If the target type defines a static ::Create() method that takes that input, use that.
- Constructor conversion. If the target type defines a constructor that takes your input, use that.
- Cast conversion. If the target type defines a implicit or explicit cast operator from the source type, use that. If the source type defines an implicit or explicit cast operator to the target type, use that.
- IConvertible conversion. If the source type defines an IConvertible implementation that knows how to convert to the target type, use that.
- IDictionary conversion. If the source type is an IDictionary (i.e.: Hashtable), try to create an instance of the destination type using its default constructor, and then use the names and values in the IDictionary to set properties on the source object.
- PSObject property conversion. If the source type is a PSObject, try to create an instance of the destination type using its default constructor, and then use the property names and values in the PSObject to set properties on the source object. . If a name maps to a method instead of a property, invoke that method with the value as its argument.
- TypeConverter conversion. If there is a registered TypeConverter or PSTypeConverter that can handle the conversion, do that. You can register a TypeConverter through a types.ps1xml file (see: $pshome\Types.ps1xml), or through Update-TypeData.
Now, see if you can figure out what these do, and why:
Hope this helps!
Lee Holmes [MSFT]
Windows PowerShell Development