Custom Collapsible Blocks in PowerShell

As much as Microsoft want you to use Visual Studio Code for PowerShell, I still love to use the IDE.

So a quick piece on something that’s quite useful….

As you will know, if you write PowerShell code in the IDE, is that it automatically detects blocks of code and lets you collapse and expand them by clicking on the + or -.

All well and good, what happens if you want a custom set? Turns out its really easy.

#region My Region
write-host "This is one region"
#endregion

#region My Second Region
write-host "This is my second region"
#endregion

And voila, we have blocks to collapse!

Ok so cool, now we have lots of blocks, but man… why doesnt the ISE have an option to collapse all? WHY!

So doing a quick search of the interwebz you can run:

$psISE.CurrentFile.Editor.ToggleOutliningExpansion()

Which will collapse all and expand all.

Ok sweet…. lets add that as a …. wait, we cant add custom buttons? WHY!

So…. You can google search on how to add custom menu options if you want, that easy enough to do… Or you can just add a quick and nasty function to your IDE profile to so it.

I’m lazy, and run code under multiple users so I put my block in the AllUsersAllHosts profile

You can do this, in the IDE, by typing in: notepad.exe $profilel.AllUsersAllHosts

function collapse
	{
	$psISE.CurrentFile.Editor.ToggleOutliningExpansion()
	}

Save the profile, restart the IDE and you can just type collapse (or whatever you want to call the function) to collapse all blocks, or expand all blocks, at once.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.