Time to read: ~ 3.5 minutes
Let’s take the a moderation of FizzBuzz as an example. Let’s get the running totals of the fizz buzz numbers.
The initial way that I would do this would be a straight up
Now what happens if we don’t want to use switch? What happens if we tried to do this with script blocks instead?
I’ve created 3 different script blocks here just for ease of use. If you want to create a single script block to do this then I encourage it! Let me know how you get on.
We’re also passing in the parameter into the script block by passing it in the brackets of the
Quick little tip, if you want to see what you can do with methods, run the method without specifying brackets
So we run the above and the results that we get are…
0 + 3 is 0 apparently…as well as 10 + 5 being 0 as well? Splendid!
Why? Let’s try troubleshooting it first.
When trying to figure out what’s wrong, I figured I’d move the Modulus operator to be inside the script block and just return the value instead of saving the value to the variable.
Lo and behold it works!…ish
There’s something subtle that I took from this and it’s probably best I show you. If you take a look at the screenshot above and you can see the numbers are aligned to the left. Yet I declared my variables to be
ints and that means that they should be right aligned like this:
Also I’m sure you noticed the lack of 0’s in the screenshot? Another confirmation.
We can see that an
int defaults to 0 but a
string defaults to nothing.
My take away from this is that my script blocks are able to find my variables that I set at the start of the script. They just seem to have a problem with updating them for me…
Then let’s just update the variables from the value output by the script blocks, shall we? All we need for this is
$var = $Scriptblock.Invoke().
Good but bloated
Can we make that leaner? Let’s try putting the modulus check back up into the script block again.
Which gives us the results:
Dammit! We’re back to the default values again; we’re not outputting any values from the script blocks when they don’t match the modulus. So we’re getting 0s back.
Because our script blocks doesn’t execute any code when
$Num is not equal to 2, it returns nothing and that nothing is getting converted to a 0!
A quick change to return the variable no matter what and we should be good to go!
But does it work?
Yes! 0 + 3 is 3; 3 + 6 is 9; 9 + 9 is 18!
PowerShell will check up the scope for a variable but will not check downwards.
So our script block will check upwards for the variable we set and find it. BUT if you update the variable inside the script block, then PowerShell won’t check downwards and get the updated value.
He can explain this to a better standard than I can. Think I’ll just learn by failing until I get to his level 🙂