Time to read: ~ 3 minutes
It’s Been A While But…
…recently, I ran into an issue in PowerShell that, if it had been in SQL, I would have solved it quite handily with some Dynamic SQL.
“Alas, this is PowerShell” I thought to myself. “And there is no way that one knows of that one can create dynamic commands that can be built up itself!“.
Now, there is two things that you have to realise for when I’m thinking to myself:
- I think more fancy that I am in real life, and
- I’m nearly always wrong!
So please see below for my example problem and the “dynamic PowerShell” created to overcome the issue!
My Example Issue…
…involves a basic json file.
Now, let’s say that we need to find the values of a certain property, let’s say “IsYAVowel”. Easy enough, we can just use something like the following:
$jsonFile = Get-Content -Path .\BasicJson | ConvertFrom-Json $jsonFile.Database.View.IsYAVowel
But that doesn’t really help our cause of needing to use dynamic PowerShell…so I’m going to ignore it and use this more “verbose” way instead!
Like we said, easy enough. We are basically…
- changing the json into a object,
- we’re selecting and expanding the Database property,
- selecting and expanding the View property, and
- finally selecting and expanding the IsYAVowel property to get it’s value.
What we cannot do is either of the following:
So what are we supposed to do when we are asked to select the value from a property when we are given the path like these:
- “Database.View.IsYAVowel“, or
- “Database.Table.Fruit“, or
- “Database.DatabaseName“, or even
That is where a Dynamic way of PowerShell can come in handy!
Splitting the string…
… seems simple enough.
Now that we have an ordered list of properties we can place them into our string.
You know that it won’t be as simple as this but we’re going to try to call that directly and see what happens.
$Stmt & $Stmt
How can we get PowerShell to treat that as a Script Block?
Well it turns out that the answer is pretty damn simple (once you know what to look for).
PowerShell, like other languages, has types and one of those types is
[scriptblock] which has the lovely method called
Create(). If we look at the Overload Definition (by running the method without the accompanying brackets) we can see that all it needs is a string so let’s pass our string script in!
[scriptblock]::Create [scriptblock]::Create($Stmt) $ActualStmt = [scriptblock]::Create($Stmt)
It looks just like a string now, right? Has that done any bit of difference? Well let’s see…
And now, we can execute our $ActualStmt and…
And we now have “dynamic PowerShell”, or as they’re normally called, Scriptblocks!