Today I would like to share “creative” way of abusing dynamic parameters in PowerShell I came up with yesterday. All started with challenging question on PowerShell TechNet forum. But before I get there I would like to show also why and how you would use them normally, so that you know why I would call my trick an “abuse”. All examples will be pretty naive and not production-oriented. For better examples – lookup poshcode, especially Joel’s and Oisin’s magical tools. Few to start with:
There are two things, that make some operations with classes/ types smooth in PowerShell. First of all we have type conversion, that will do (almost) everything that is possible to “translate” data into the type that we select. Second element that is handy at times are type accelerators, that work as aliases for types.
During PowerShell Deep Dive I found out (thank you, Kirk!) something that I was not aware of before: type accelerators are similar to aliases also when it comes to priority order: if there is type accelerator available that matches to string provided – you will get it instead of “real” type. That basically means that you can fully replace “real” type with your own implementation, all you need to do is to add type accelerator with the name of needed type and redirect it to your own type.
There are some really nice use cases of that, but today I would like to abuse it.
Where we are?
How many time have I heard this question from other PowerShell enthusiasts: “when cmd.exe is going to die”. Or at best “when will PowerShell.exe become default when user asks for command line”. It’s not so in Windows 8 Developer Preview, not sure what to expect in final release, but kind of don’t expect it to happen anytime soon. What is most frustrating for some is the fact, that server core still expects us to type “powershell.exe” once we boot.