April.Fools

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. Smile

Read more…

PowerShell vNext: AST.

What is that?

There is one addition in PowerShell vNext that I look really forward to. In v2 we have parser available. It makes work with PowerShell code easier. But PowerShell team haven’t stopped there. AST (Abstract Syntax Tree) is new concept (at least – to me) and it makes parsing code more interesting: instead of stream of tokens (which is still there with AST and is also more accurate than v2 precedents) we get tree of syntax: from Script to single Statement. Browsing thru that tree may be very hard at first. I tried to use view that seems natural for that kind of complex structures: Format-Custom. The problem that I went into was the fact, that each AST contains “Extent” and “Parent” property. And those properties keep whole code which makes Format-Custom lengthy and impractical. So my first step was to create .ps1xml files to make format and object themselves bit different. I hidden two properties I think are not very useful. You can still access them using psbase on each object – and that exactly the information you get if you try to access them directly. Next step I took was to create simple function that would wrap .NET call to System.Management.Automation.Language.Parser static methods (ParseInput, ParseFile) and make use of them more natural and PowerShell-ish. Then I packed it all in the module, so that I could paste it somewhere and let others use it and complain about things I did wrong (like using global scope to store tokens/ errors).

Read more…