Dynamic Casting

  • Comments 4

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]

Or (using a STRING instead of a TYPE):

$d = Read-Host –Prompt "TYPE:"

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


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

Leave a Comment
  • Please add 8 and 2 and type the answer here:
  • Post
  • 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.



  • 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? ;-)

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


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

  • Suppose you want to do something like:

     $t = Read-host -Prompt "Type: "

     $v = Read-host -Prompt "Value: "

     [$t] $myVar = $v

    In this case -as doesn't help. What to do?

Page 1 of 1 (4 items)

Dynamic Casting