Using PowerShell Regions

Using PowerShell Regions

Q: What are Windows PowerShell Regions?

A: Typically, when you create a large PowerShell script, you have modules of code, and it can sometimes be very overwhelming and hard to navigate with all the code always visible.

PowerShell Regions let you place blocks of code into a collapsible "region" reducing what is displayed on screen until you actually want to see that region of code. Then you simply click to view the content of the region. To create a region use this command:

#region 

and to end it:

#endregion

For example, here is a complete region:

#region Background job
$Trigger = New-JobTrigger –Daily –At 2am
Register-ScheduledJob –Name MyScheduledJob –ScriptBlock {Get-Process} –Trigger $Trigger
Get-ScheduledJob
(Get-ScheduledJob –Name MyScheduledJob).JobTriggers
Get-ScheduledJob –Name MyScheduledJob
Unregister-ScheduledJob -Name MyScheduledJob
#endregion

This is what regions look like in your code. Notice all are collapsed except the Background job region. Notice the line numbers are still accurate which gives you an idea of the number of lines in each region.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish