Dynamic Casting

We’ve seen a couple requests for this on our internal mailing lists so I thought other people would be interested.

There are times when you want to do something like:

$d = [DateTime]
[$d]”12/25/2007″

Or (using a STRING instead of a TYPE):

$d = Read-Host –Prompt “TYPE:”
[$d]”12/25/2007″

Of course if either of these worked – I wouldn’t be writing this blog. Jim Truher provided the solution: the –AS operator.

The –AS operator casts an object to a particular type. Now in a traditional language, casting is thin operation which basically tells the compiler to think about things differently. In PowerShell, the –AS operator is a way to tell PowerShell want you want happen and then we do whatever we can do to make your wishes true. (e.g. we do casting, coercion, conversion, etc).

PS>$d = [DateTime]
PS>”12/25/2007″ -as $d

Tuesday, December 25, 2007 12:00:00 AM

PS>$d = Read-Host “Type”
Type: DateTime
PS>”12/25/2007″ -as $d

Tuesday, December 25, 2007 12:00:00 AM

Enjoy!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx