Welcome to MSDN Blogs Sign in | Join | Help

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

Published Monday, October 29, 2007 5:14 PM by PowerShellTeam

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Dynamic Casting

Sounds great - really looking forward to all the new goodies:-)

But instead (as well) as dynamic casting, can we have dynamic locales?  

12/25/2007 is not a valid date in my environment and you have no idea how inconvenient it is to remember that valid date strings will (sometimes!) be rejected by a cast to [datetime].

Sorry to go on about it.  I know I've brought this up before, but it's the only REAL bad thing to have crept in to v1.0 IMO and I wish you guys would make it better.

Thanks

Chris

Monday, October 29, 2007 5:17 PM by Chris Warwick

# re: Dynamic Casting

This is not working for me.  Powershell keeps going into an endless loop.  The command I tried is "Joe Brinkman" -as "[PowerShellExpert]" and it just isn't working?  What am I doing wrong? ;-)

Monday, October 29, 2007 6:38 PM by Joe Brinkman

# re: Dynamic Casting

I blogged about this a few weeks ago, explaining how it can be used to ease the pain of using Enums in powershell:

http://www.nivot.org/2007/10/12/UsingEnumeratedTypesEnumsInPowerShell.aspx

This is probably a more practical example of dynamic casting. ;-)

Tuesday, October 30, 2007 10:30 PM by Oisin Grehan

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker