As a consultant I move from project to project, usually meeting a bunch of new people each time, imparting some wisdom, and moving on. One of the highlights for me is what I learn from the people that I encounter along the way.
And so it was that I met Neil East in Canberra, and he shared with me his amazing PowerShell code toggle.
The point of this is that it’s a MIND-BOGGLINGLY simple way of replacing a line (or more) of a script with an alternative. Typically this is when you’re developing and might want to run some code in a “read only” mode, or some other debugging process, and you might have a need to toggle back and forth many times.
Neil’s trick exploits that PowerShell has two different ways of commenting-out code:
The most common is just starting a line with a “#”.
# This line won't be actioned
The other is to wrap one or more lines in a “<#" and a "#>“.
<# This will be skipped too #>
Neil’s trick uses both, and all you need to do is delete the first “<” – shown highlighted below – to activate the second chunk of code.
<# Write-host "that" <#> Write-host "this" #>
If you paste the above into a PowerShell window it will report “this”.
Here’s the same code, minus the first “<“, and if you run it now you’ll see it reports “that”:
# Write-host "that" <#> Write-host "this" #>
I think it’s amazing, and Neil kindly gave me permission to share it. Enjoy. (Thanks Neil.)