Powershell Stacks

Phil Factor shows how to use Powershell’s push and pop methods to create an expression evaluator:

I use stacks for writing expression analysers. Generally I like at least two stacks, probably up to four. They tend to be different sizes and may have other differences. If written as objects, the code becomes much cleaner and easier to read. Why do I write expression analysers? You might imagine that you would never need such a thing, but once you have one, reasons for using it just keep appearing. They are handy for parsing document-based hierarchical data structures, for parsing grammars and for creating Domain-Specific Languages (DSLs). A DSL is handy when you’re writing a complex application because it cuts down dependencies, and allows you to develop scripts for complex workflows without recompiling .

What I describe here is a cut-down version of what I use, just to illustrate the way of creating and using stacks. I extend this basic algorithm, originally from Dijstra’s shunting algorithm, into a complete language interpreter. All it needs is a third stack to implement block iterations and ‘while’ loops. Why not use PowerShell itself as your DSL? I’ve tried that, but my experience is that it is pretty-well impossible to eliminate script-injection attacks, and I also find that there isn’t quite enough control.

For a more prosaic usage of the stack in Powershell (as well as bash), you can push your current location, move to a new directory, perform some action in that new directory, and pop your old location off the stack to go back to where you were before.  This is particularly useful for those Powershell modules and cmdlets which leave you in a different directory from where you started.

Related Posts

Config Options For Checks In DBAChecks

Rob Sewell explains a new features in dbachecks: You can see the name, the current value and the description Ah thats cool he said so How Do I Know Which Configuration Is For Which Check? Well, you just…. , you know…… AHHHHHHH Rob then made this possible.  Click through to see how you can determine […]

Read More

Creating Azure SQL Database Managed Instances Via ARM Templates

Jovan Popovic shows how us how to build a Managed Instance of Azure SQL Database using Powershell and an ARM template: Values that you need to change in this request are: name – name of your Azure SQL Managed Instance (don’t include domain). properties/administratorLogin – SQL login that will be used to connect to the […]

Read More


August 2016
« Jul Sep »