IT Channel.com

Using PowerShell ISE and alias cmdlets

By null

Solutions provider takeaway: One of PowerShell 2.0's new features is the Integrated Scripting Environment (ISE), which can help solutions providers write commands and scripts.PowerShell ISE's capabilities include being able to view and edit multiple lines in the command pane. There is also information on the role that alias cmdlets play in alias administration.

About the book:
This chapter excerpt on Automating Tasks Using PowerShell Scripting (download PDF) is taken from the book Windows Server 2008 R2 Unleashed. Solutions providers can use this book to learn about Windows Server 2008 R2 migration, administration, deployment and troubleshooting. This book also provides information on management and security tools and features, such as Hyper-V's Live Migration.

PowerShell ISE

Another new feature that was introduced in PowerShell 2.0 is called the Integrated Scripting Environment (ISE). The ISE, as shown in Figure 21.1, is a Windows Presentation Foundation (WPF)--based host application for Windows PowerShell. Using the ISE, an IT professional can both run commands and write, test, and debug scripts.

Additional features of the ISE include the following:

FIGURE 21.1 The PowerShell ISE.

The PowerShell ISE is an optional feature in Windows Server 2008 R2. To use the ISE, it first must be installed using the Add Features Wizard. Because the ISE requires the .NET Framework 3.5 with Service Pack 1, the Server Manager will also install this version of the .NET Framework if it is not already installed. Once installed, use either of the following methods to start it:

  1. Start Windows PowerShell ISE by clicking Start, All Programs, Accessories, Windows PowerShell, and then click Windows PowerShell ISE or Windows PowerShell ISE (x86).
  2. Or execute the powershell_ise.exe executable.

ISE Requirements

The following requirements must be met to use the ISE:

Note:
Being a GUI-based application, the PowerShell ISE does not work on Server Core installations of Windows Server.

Variables

A variable is a storage place for data. In most shells, the only data that can be stored in a variable is text data. In advanced shells and programming languages, data stored in variables can be almost anything, from strings to sequences to objects. Similarly, PowerShell variables can be just about anything.

To define a PowerShell variable, you must name it with the $ prefix, which helps delineate variables from aliases, cmdlets, filenames, and other items a shell operator might want to use. A variable name can contain any combination of alphanumeric characters (a--z and 0--9) and the underscore (_) character. Although PowerShell variables have no set naming convention, using a name that reflects the type of data the variable contains is recommended, as shown in this example:

PS C:\ > $Stopped = get-service | where {$_.status -eq "stopped"}
PS C:\ > $Stopped

<align="center">Status<align="center">Name<align="center">DisplayName

Stopped ALG Application Layer Gateway Service
Stopped Appinfo Application Information
Stopped AppMgmt Application Management
Stopped aspnet_state ASP.NET State Service
Stopped AudioEndpointBu… Windows Audio Endpoint Builder
Stopped Audiosrv Windows Audio

...

As you can see from the previous example, the information that is contained within the $Stopped variable is a collection of services that are currently stopped.

Note:
A variable name can consist of any characters, including spaces, provided the name is enclosed in curly braces ({ and } symbols).

Aliases

Like most existing command-line shells, command aliases can be defined in PowerShell. Aliasing is a method that is used to execute existing shell commands (cmdlets) using a different name. In many cases, the main reason aliases are used is to establish abbreviated command names in an effort to reduce typing. For example:

PS C:\ > gps | ? {$_.Company -match ".*Microsoft*"} | ft Name, ID, Path --Autosize

The preceding example shows the default aliases for the Get-Process, Where-Object, and Format-Table cmdlets.

Alias cmdlets

In PowerShell, several alias cmdlets enable an administrator to define new aliases, export aliases, import aliases, and display existing aliases. By using the following command, an administrator can get a list of all the related alias cmdlets:

PS C:\ > get-command *-Alias

<align="center">CommandType<align="center">Name<align="center">Definition

Cmdlet Export-Alias Export-Alias [-Path] <String...
Cmdlet Get-Alias Get-Alias [[-Name] <String[]...
Cmdlet Import-Alias Import-Alias [-Path] <String...
Cmdlet New-Alias New-Alias [-Name] [...
Cmdlet Set-Alias Set-Alias [-Name] [...

Use the Get-Alias cmdlet to produce a list of aliases available in the current PowerShell session. The Export-Alias and Import-Alias cmdlets are used to export and import alias lists from one PowerShell session to another. Finally, the New-Alias and Set-Alias cmdlets allow an administrator to define new aliases for the current PowerShell session.

Creating Persistent Aliases

The aliases created when using the New-Alias and Set-Alias cmdlets are valid only in the current PowerShell session. Exiting a PowerShell session discards any existing aliases. To have aliases persist across PowerShell sessions, they can be defined in a profile file, as shown in this example:

set-alias new new-object
set-alias time get-date
...

Although command shortening is appealing, the extensive use of aliases isn't recommended. One reason is that aliases aren't very portable in relation to scripts. For example, if a lot of aliases are used in a script, each alias must be included via a Set-Aliases sequence at the start of the script to make sure those aliases are present, regardless of machine or session profile, when the script runs.

However, a bigger concern than portability is that aliases can often confuse or obscure the true meaning of commands or scripts. The aliases that are defined might make sense to a scripter, but not everyone shares the logic in defining aliases. So if a scripter wants others to understand their scripts, they shouldn't use too many aliases.

Note:
If aliases will be used in a script, use names that other people can understand. For example, there's no reason, other than to encode a script, to create aliases consisting of only two letters.

Scopes

A scope is a logical boundary in PowerShell that isolates the use of functions and variables. Scopes can be defined as global, local, script, and private. They function in a hierarchy in which scope information is inherited downward. For example, the local scope can read the global scope, but the global scope can't read information from the local scope. Scopes and their use are described in the following sections.

Global

As the name indicates, a global scope applies to an entire PowerShell instance. Global scope data is inherited by all child scopes, so any commands, functions, or scripts that run make use of variables defined in the global scope. However, global scopes are not shared between different instances of PowerShell.

The following example shows the $Processes variable being defined as a global variable in the ListProcesses function. Because the $Processes variable is being defined globally, checking $Processes.Count after ListProcesses completes returns a count of the number of active processes at the time ListProcesses was executed:

PS C:\ > function ListProcesses {$Global:Processes = get-process}
PS C:\ > ListProcesses
PS C:\ > $Processes.Count
37

Note:
In PowerShell, an explicit scope indicator can be used to determine the scope a variable resides in. For instance, if a variable is to reside in the global scope, it should be defined as $Global:variablename. If an explicit scope indicator isn't used, a variable resides in the current scope for which it's defined.

Local

A local scope is created dynamically each time a function, filter, or script runs. After a local scope has finished running, information in it is discarded. A local scope can read information from the global scope but can't make changes to it.

The following example shows the locally scoped variable $Processes being defined in the ListProcesses function. After ListProcesses finishes running, the $Processes variable no longer contains any data because it was defined only in the ListProcesses function. Notice how checking $Processes.Count after the ListProcesses function is finished produces no results:

PS C:\ > function ListProcesses {$Processes = get-process}
PS C:\ > ListProcesses
PS C:\ > $Processes.Count
PS C:\ >

Script

A script scope is created whenever a script file runs and is discarded when the script finishes running. To see an example of how a script scope works, create the following script and save it as ListProcesses.ps1:

$Processes = get-process
write-host "Here is the first process:" -Foregroundcolor Yellow
$Processes[0]

After creating the script file, run it from a PowerShell session. The output should look similar to this example:

PS C:\ > .\ListProcesses.ps1
Here is the first process:

<align="center">Handles<align="center">NPM(K)<align="center">PM(K) <align="center">WS(K) <align="center">VM(M) <align="center">CPU(s) <align="center">Id<align="center">ProcessName

105 5 1992 4128 32 916 alg

PS C:\> $Processes[0]
Cannot index into a null array.
At line:1 char:12
+ $Processes[0 <<<< ]
PS C:\>

Notice that when the ListProcesses.ps1 script runs, information about the first process object in the $Processes variable is written to the console. However, when you try to access information in the $Processes variable from the console, an error is returned because the $Processes variable is valid only in the script scope. When the script finishes running, that scope and all its contents are discarded.

What if an administrator wants to use a script in a pipeline or access it as a library file for common functions? Normally, this isn't possible because PowerShell discards a script scope whenever a script finishes running. Luckily, PowerShell supports the dot-sourcing technique, a term that originally came from UNIX. Dot sourcing a script file tells PowerShell to load a script scope into the calling parent's scope.

To dot source a script file, simply prefix the script name with a period (dot) when running the script, as shown here:

PS C:\ > . .\coolscript.ps1

Private

A private scope is similar to a local scope, with one key difference: Definitions in the private scope aren't inherited by any child scopes.

The following example shows the privately scoped variable $Processes defined in the ListProcesses function. Notice that during execution of the ListProcesses function, the $Processes variable isn't available to the child scope represented by the script block enclosed by { and } in lines 6--9.

PS C:\> function ListProcesses {$Private:Processes = get-process
>> write-host "Here is the first process:" -Foregroundcolor Yellow
>> $Processes[0]
>> write-host
>>>> &{
>> write-host "Here it is again:" -Foregroundcolor Yellow
>> $Processes[0]
>> }
>> }
>>PS C:\> ListProcesses
Here is the first process:

<align="center">Handles<align="center">NPM(K) <align="center">PM(K) <align="center">WS(K) <align="center">VM(M) <align="center">CPU(s) <align="center">Id <align="center">ProcessName

105 5 1992 4128 32 916 alg

Here it is again:
Cannot index into a null array.
At line:7 char:20

+           $Processes[0 <<<< ]
PS C:\>

This example works because it uses the & call operator. With this call operator, you can execute fragments of script code in an isolated local scope. This technique is helpful for isolating a script block and its variables from a parent scope or, as in this example, isolating a privately scoped variable from a script block.

About the authors:

Rand Morimoto has been in the IT industry for more than 25 years and is the president of Convergent Computing, an IT-consulting firm. Morimoto has also co-authored Exchange Server 2010 Unleashed.

Michael Noel is an IT expert and partner at Convergent Computing and co-wrote Microsoft SharePoint 2007 Unleashed.

Chris Amaris cofounded Convergent Computing and serves as the chief technology officer. Amaris has also co-authored Microsoft Exchange Server 2007 Unleashed.

Omar Droubi has been in the computer industry for more than 15 years and has co-authored Windows 2003 Unleashed.

Ross Mistry has spent more than a decade in the computer industry and has also published Microsoft SQL Server 2008 Management and Administration.

Providers and Drives

Most computer systems are used to store data, often in a structure such as a file system. Because of the amount of data stored in these structures, processing and finding information can be unwieldy. Most shells have interfaces, or providers, for interacting with data stores in a predictable, set manner. PowerShell also has a set of providers for presenting the contents of data stores through a core set of cmdlets. You can then use these cmdlets to browse, navigate, and manipulate data from stores through a common interface. To get a list of the core cmdlets, use the following command:

PS C:\> help about_core_commands
...
ChildItem CMDLETS
Get-ChildItem
CONTENT CMDLETS
Add-Content
Clear-Content
Get-Content
Set-Content
...

To view built-in PowerShell providers, use the following command:

PS C:\> get-psprovider

<align="center">Name<align="center">Capabilities<align="center">Drives

WSMan Credentials {WSMan}
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess {C, D, E}
Function ShouldProcess {Function}
Registry ShouldProcess, Transactions {HKLM, HKCU}
Variable ShouldProcess, Transactions {Variable}
Certificate ShouldProcess, Transactions {cert}

PS C:\>

The preceding list displays not only built-in providers, but also the drives each provider currently supports. A drive is an entity that a provider uses to represent a data store through which data is made available to the PowerShell session. For example, the Registry provider creates a PowerShell drive for the HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER Registry hives.

To see a list of all current PowerShell drives, use the following command:

PS C:\> get-psdrive

<align="center">Name<align="center"> Used (GB)<align="center"> Free (GB)<align="center"> Provider (GB)<align="center">Root(GB)

Alias Alias
C 68.50 107.00 FileSystem C: \
cert Certificate \
D 8.98 1.83 FileSystem D:\
E FileSystem E:\
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan

PS C:\>


Automating Tasks Using PowerShell Scripting
  PowerShell commands in Windows Server 2008 R2
  PowerShell remoting in Windows Server 2008 R2
  Using PowerShell ISE and alias cmdlets
  PowerShell profiles in Windows Server 2008 R2

Printed with permission from Sams Publishing. Copyright 2010. Windows Server 2008 R2 Unleashed by Rand Morimoto, Michael Noel, Omar Droubi and Ross Mistry. For more information about this title and other similar books, please visit Sams Publishing.

21 Apr 2010

All Rights Reserved, Copyright 2006 - 2024, TechTarget | Read our Privacy Statement