Chapter 19. Integrated Scripting Environment

Introduction

While text-mode PowerShell is great for its efficiency and automation, there's not much to be said for its user interface. Most of Windows' key combinations don't work. Text selection and editing don't work. Rectangular text selection is strange, as is the lack of support for freely-resizing the console window.

All of these are simple side-effects of PowerShell.exe being a console application. They impact every console application in Windows, and likely always will.

Aside from the user interface oddities, the fatal flaw with console applications comes from their lack of support for the Unicode standard: the way that most international languages represent their alphabet. While the Windows console supports a few basic non-English characters (such as accented letters), it provides full support for very little else.

1 comment

  1. Johannes Rössel Posted 15 days and 6 hours ago

    Changing the console window to a TrueType font, such as Lucida Console or Consolas, enables it to display Unicode, though. Combining characters won't work as will complex scripts but at least you'll get support way beyond the archaic OEM character set, including things like Cyrillic and Greek that display fine.

    However, it's probably debatable whether this book should go into detail on the fact that the font choice of the console window dictates its character set and Unicode support. The commands in Example 1.8 thankfully include a sane font choice as I notice now; otherwise I'd have suggested to include it :-)

Add a comment

This proves to be quite a problem for world-wide administrators! Since typing international characters directly at the command line was so difficult, administrators in many countries were forced to write scripts in Notepad in order to get full Unicode support, and then use PowerShell to run the scripts. Even if the command was ultimately only a single line long.

PowerShell version two resolves these issues by introducing the Integrated Scripting Environment (ISE.)

Figure 19.1. Windows PowerShell Integrated Scripting Environment

Windows PowerShell Integrated Scripting Environment


1 comment

  1. David "Makovec" Moravec Posted 10 days and 23 hours ago

    Figure title: 'Powershell' -> 'PowerShell'

Add a comment

It gives PowerShell the user interface you would expect of a modern application, supports full Unicode input, multiple tabbed sessions, and provides a great experience for interactive debugging.

Conceptually, the Integrated Scripting Environment consists of three main components:

Scripting Pane

The scripting pane is the top pane of the ISE, and is geared toward multi-line script editing and creation. It offers line numbering, syntax highlighting, and supports a great debugging experience.

One unique aspect of the scripting pane is that it supports selective execution: the ability to run just what you've highlighted rather than the entire script you're working on. This makes script authoring a breeze. As you start to write your script, you can interactively experiment with commands until you get them right. Once they work as expected, you can keep them, move on, and then continue to build your script one piece at a time. As you've come to expect from PowerShell's console shell, script editing in the scripting pane even supports tab completion of commands, parameters, paths, and more.

Output Pane

The output pane sits in the middle of the ISE, and shows output from commands run both in the scripting pane and command pane. Unlike PowerShell's console shell, text selection in the output pane acts like text selection in regular windows application.

Command Pane

The command pane is where you'll spend most of your interactive sessions in the ISE, and sits in the bottom of the application. Like the command prompt in the PowerShell console, the command pane supports tab completion. Unline the command pane in the console window, it supports Windows' standard hotkeys, text selection, syntax highlighting, and more.

If you find your command growing too long, you can press Shift + Enter to enable multi-line editing for the current command.

In addition to these features, the PowerShell ISE offers extensive customization, scripting, and remoting support.

Debug a Script

Problem

You want to use PowerShell's debugging commands through an interface more friendly than its *-PsBreakpoint cmdlets.

Solution

Use the Debug menu in the Integrated Scripting Environment to add and remove breakpoints, and manage debugging behavior when PowerShell reaches a breakpoint.

Figure 19.2. Debugging options in the Integrated Scripting Environment

Debugging options in the Integrated Scripting Environment


Discussion

The PowerShell Integrated Scripting Environment (ISE) gives you a rich set of interactive graphical debugging commands to help you diagnose errors in your scrpts. It exposes these through the Debug menu, and behaves like many other graphical debugging environments you may have experience with.

1 comment

  1. Tome Tanasovski Posted 12 days and 22 hours ago

    Should be noted that this is only available after saving the document. The cmdlets for breakpoints tell you this, but the ISE does not.

Add a comment

To set a breakpoint, first save your script. Then, select the "Toggle Breakpoint" menu item, the "Toggle Breakpoint" option that shows when you right-click in the left-hand margin of the ISE, or press F9. Once PowerShell hits that line in your script, it pauses to let you examine variables, script state, and whatever else interests you. To control the flow of execution, you can use the stepping commands: Step Over, Step Into, and Step Out.

1 comment

  1. Tome Tanasovski Posted 12 days and 22 hours ago

    Might be worth noting that "Toggle Breakpoint" is also available by right-clicking

Add a comment

Step Over continues to the next line of the script, executing (but not debugging into) any function calls that you come across. Step Into continues to the next line of the script, debugging into any function calls that you come across. If you are in a function, the Step Out command lets PowerShell complete execution of the function, and resumes debugging once the function completes.

One unique aspect of debugging in the ISE is that it builds its support entirely on the core debugging cmdlets discussed in Chapter 14, Debugging. Changes that you make from the debugging menu (such as adding a breakpoint) get immediately reflected in the cmdlets (such as listing breakpoints.) Likewise, breakpoints that you add or modify from the integrated command line show up in the user interface as though you had created them from the debug menu itself.

Note

In fact, the features exposed by PowerShell's breakpoint cmdlets in many cases surpass the functionality exposed by the ISE's debug menu. For example, the Set-PsDebug cmdlet supports command breakpoints, conditional breakpoints, variable breakpoints, and much more. For more information about the Set-PsDebug cmdlet, see the section called “Set a Script Breakpoint”.

Unlike most graphical debugging environments, the PowerShell ISE makes it incredibly easy to investigate the dynamic state of your script while you are debugging it. For more information about how to investigate the state of your script while debugging, see the section called “Investigate System State While Debugging”.

1 comment

  1. AndrewTearle Posted 16 days and 23 hours ago

    For more information about (to) investigate ( how to ?)

Add a comment

Customize Text and User Interface Colors

Problem

You want to change the color scheme of the Integrated Scripting Environment, or colors used for syntax highlighting.

Solution

Review the properties of the $psISE.Options automatic variable, and customize the ones you want. For example, to give the output pane the same appearance as the PowerShell console:

$psISE.Options.OutputPaneBackgroundColor = "#012456"
$psISE.Options.OutputPaneForegroundColor = "#EEEDF0"
$psISE.Options.OutputPaneTextBackgroundColor = "#012456"

Discussion

While working in the Integrated Scripting Environment (ISE), you might sometimes wonder, "Where is the Options dialog?"

The answer is that there isn't one. Instead, the ISE offers a wealth of configuration option through its $psISE automatic variable.

PS > $psISE.Options | Format-List


SelectedScriptPaneState       : Top
ShowToolBar                   : True
TokenColors                   : {[Attribute, #FFADD8E6], [Command, #FF0000FF], 
                                [CommandArgument, #FF8A2BE2], [CommandParameter
                                , #FF000080]...}
DefaultOptions                : Microsoft.PowerShell.Host.ISE.ISEOptions
FontSize                      : 12
FontName                      : Consolas
ErrorForegroundColor          : #FFFF0000
ErrorBackgroundColor          : #00FFFFFF
WarningForegroundColor        : #FFFF8C00
WarningBackgroundColor        : #00FFFFFF
VerboseForegroundColor        : #FF0000FF
VerboseBackgroundColor        : #00FFFFFF
DebugForegroundColor          : #FF0000FF
DebugBackgroundColor          : #00FFFFFF
OutputPaneBackgroundColor     : #FF012456
OutputPaneTextBackgroundColor : #FF012456
OutputPaneForegroundColor     : #FFEEEDF0
CommandPaneBackgroundColor    : #FFFFFFFF
ScriptPaneBackgroundColor     : #FFFFFFFF
ScriptPaneForegroundColor     : #FF000000
ShowWarningForDuplicateFiles  : True
ShowWarningBeforeSavingOnRun  : True
UseLocalHelp                  : True
CommandPaneUp                 : False

You can change these options as easily as you change any other automatic variable—by assigning new values to its properties (as shown in the solution.) To make these changes affect all of your ISE sessions, simply store them in the host-specific profile file for the ISE. To edit this file, simply type: ise $profile.CurrentUserCurrentHost.

In addition to user interface customization, the ISE also lets you customize the colors it uses for syntax highlighting. It exposes these settings through the $psISE.Options.TokenColors automatic variable. For example, to change the coloring of attributes (such as the [Parameter()] statement) to be more like regular types, type:

$psIse.Options.TokenColors["Attribute"] = $psIse.Options.TokenColors["Type"]

For more information about modifying your PowerShell profile, see the section called “Customize Your Shell, Profile, and Prompt”.

Connect to a Remote Computer

Problem

You want to create a new tab in the Integrated Scripting Environment that represents a connection to a remote computer.

Solution

Click the "New Remote PowerShell Tab" icon in the toolbar or File menu.

Discussion

One of the features most requested for the PowerShell console application is support for multiple tabs and multiple sessions. As such, multi-tab support in the ISE is prominent—and gets a unique treatment.

To create a new tab that represents a local PowerShell session, simply click the "New PowerShell Tab" icon in the toolbar or File menu. If you want to connect to a remote computer instead, just click the "New Remote PowerShell Tab" menu or toolbar icon.

Once you've connected a remote PowerShell tab, interacting with a remote system is just like interacting with a local one. Prompts from the remote system show up like prompts from the local system, as do progress bars, credential requests, and PowerShell's other feedback mechanisms.

For more information about PowerShell Remoting, see Chapter 29, Remoting.

Extend ISE Functionality Through its Object Model

Problem

You want to customize the PowerShell ISE to add your own functionality and features.

Solution

Explore and modify properties of the $psISE automatic variable to interact with the ISE's object model. For example, to clean up trailing spaces from the script you are currently editing:

$psISE.CurrentFile.Editor.Text = 
    $psise.CurrentFile.Editor.Text -replace '(?m)\s+$',''

Discussion

In addition to the features already available, the PowerShell ISE offers many additional customization opportunities through its object model. The object model exposes the nuts and bolts you need to create your own functionality—and makes it available through the $psISE automatic variable. the section called “Add an Item to the Tools Menu” demonstrates one aspect of the object model by showing how to add items to the Add-ons menu.

As with other .NET object models, the Get-Member and Format-List cmdlets are the keys to exploring the ISE's object model. At its first level, the object model gives you access to the current file, PowerShell tab, and ISE options:

PS > $psISE | Format-List


CurrentPowerShellTab : Microsoft.PowerShell.Host.ISE.PowerShellTab
CurrentFile          : Microsoft.PowerShell.Host.ISE.ISEFile
Options              : Microsoft.PowerShell.Host.ISE.ISEOptions
PowerShellTabs       : {PowerShell 1}

For example, the $psISE.CurrentFile.Editor variable provides programmatic access to the text and behavior of the current scripting pane:

PS > $psISE.CurrentFile.Editor | Get-Member

   TypeName: Microsoft.Windows.PowerShell.Gui.Internal.ScriptEditor
   
Name             MemberType Definition
----             ---------- ----------
PropertyChanged  Event      System.ComponentModel.PropertyChangedEventHandler...
Clear            Method     System.Void Clear()
EnsureVisible    Method     System.Void EnsureVisible(int lineNumber)
Equals           Method     bool Equals(System.Object obj)
Focus            Method     System.Void Focus()
GetHashCode      Method     int GetHashCode()
GetLineLength    Method     int GetLineLength(int lineNumber)
GetType          Method     type GetType()
InsertText       Method     System.Void InsertText(string text)
Select           Method     System.Void Select(int startLine, int startColumn,...
SetCaretPosition Method     System.Void SetCaretPosition(int lineNumber, int c...
ToString         Method     string ToString()
CaretColumn      Property   System.Int32 CaretColumn {get;}
CaretLine        Property   System.Int32 CaretLine {get;}
LineCount        Property   System.Int32 LineCount {get;}
SelectedText     Property   System.String SelectedText {get;}
Text             Property   System.String Text {get;set;}

By building on the object model, you can write tools to automatically process your scripts (commenting, uncommenting), script output, and more.

For more information about working with .NET objects, see the section called “Work with .NET Objects”.

Add an Item to the Tools Menu

Problem

You want to add your own menu items and shortcuts to the Integrated Scripting Environment.

Solution

Pick a display name, action, and (optional) shortcut, then add those to the $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus collection:

$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add(
    "PowerShell Blog",
    { Start-Process http://blogs.msdn.com/PowerShell },
    "Control+Alt+B")

Discussion

As part of its extensibility features, the PowerShell ISE gives you complete access to a sub-menu of your very own: the Add-ons menu.

To work with the Add-ons menu, access the $psISE.CurrentPowerShellTab.AddOnsMenu variable.

By default, menu items that get added have no shortcuts, so you must click them to activate them. To add a typical menu shortcut that becomes active once the Add Ons menu is active, put an underscore (_) character before the letter that you want to activate your menu item.

2 comments

  1. Bernd Kriszio Posted 6 days and 3 hours ago

    That doesn't work on my Windows 7. I see no mnemonic and it doesn't work.

  2. Johannes Rössel Posted 6 days and 2 hours ago

    Bernd: It does work here. You do access the menu with the keyboard, right? When opening the “Add-ons” menu with the keyboard the mnemonics become visible. They have been hidden by default for quite some time now on Windows and only become visible in obviously keyboard-driven contexts. That is, if you open a menu with the mouse they are invisible; if you press Alt or open a context menu with the keyboard thy become visible.

Add a comment

To define a hotkey available through the entire application, supply the keys as the third argument for the Add() method. If you don't want to assign a global hotkey, use $null as the third argument.

For more information about extending the ISE, see the section called “Extend ISE Functionality Through its Object Model”.

You must sign in or register before commenting
*
*
*
*
*

Atom Icon Comments on this page or Comments on the whole book.