Windows Server 2008 R2 Unleashed (144 page)

BOOK: Windows Server 2008 R2 Unleashed
11.32Mb size Format: txt, pdf, ePub

So, to perform the transmission, objects are serialized into a series of XML (CliXML) data

elements. When the server or client receives the transmission, it converts the received

XML message into a deserialized object type. The resulting object is no longer live.

Instead, it is a record of properties based on a point in time and, as such, no longer

possesses any methods.

Remoting Requirements

To use remoting, both the local and remote computers must have the following:

. Windows PowerShell 2.0 or later

. Microsoft .NET Framework 2.0 or later

ptg

. Windows Remote Management 2.0

NOTE

Windows Remote Management 2.0 is part of Windows 7 and Windows Server 2008

R2. For down-level versions of Windows, an integrated installation package must be

installed, which includes PowerShell 2.0.

Configuring Remoting

By default, WinRM is installed on all Windows Server 2008 R2 machines as part of the

default operating system installation. However, for security purposes, PowerShell remoting

and WinRM are, by default, configured to not allow remote connections. You can use

several methods to configure remoting, as described in the following sections.

Method One

The first and easiest method to enable PowerShell remoting is to execute the

Enable-PSRemoting cmdlet. For example:

PS C:\> enable-pssremoting

Once executed, the following tasks are performed by the Enable-PSRemoting cmdlet:

. Runs the Set-WSManQuickConfig cmdlet, which performs the following tasks:

. Starts the WinRM service.

. Sets the startup type on the WinRM service to Automatic.

Understanding the PowerShell Basics

719

. Creates a listener to accept requests on any IP address.

.

21

Enables a firewall exception for WS-Management communications.

. Enables all registered Windows PowerShell session configurations to receive instruc-

tions from a remote computer.

. Registers the “Microsoft.PowerShell” session configuration, if it is not already

registered.

. Registers the “Microsoft.PowerShell32” session configuration on 64-bit computers, if

it is not already registered.

. Removes the “Deny Everyone” setting from the security descriptor for all the regis-

tered session configurations.

. Restarts the WinRM service to make the preceding changes effective.

NOTE

To configure PowerShell remoting, the Enable-PSRemoting cmdlet must be executed

using the Run As Administrator option.

ptg

Method Two

The second method to configure remoting is to use Server Manager. Use the

following steps to use this method:

1. Open Server Manager.

2. In the Server Summary area of the Server Manager home page, click Configure Server

Manager Remote Management.

3. Next, select Enable Remote Management of This Server from Other Computers.

4. Click OK.

Method Three

Finally, the third method to configure remoting is to use GPO. Use the

following steps to use this method:

1. Create a new GPO, or edit an existing one.

2. Expand Computer Configuration, Policies, Administrative Templates, Windows

Components, Windows Remote Management, and then select WinRM Service.

3. Open the Allow Automatic Configuration of Listeners Policy, select Enabled, and

then define the IPv4 filter and IPv6 filter as *.

4. Click OK.

5. Next, expand Computer Configuration, Policies, Windows Settings, Security Settings,

Windows Firewall with Advanced Security, Windows Firewall with Advanced

Security, and then Inbound Rules.

6. Right-click Inbound Rules, and then click New Rule.

7. In the New Inbound Rule Wizard, on the Rule Type page, select Predefined.

8. On the Predefined pull-down menu, select Remote Event Log Management. Click Next.

720

CHAPTER 21

Automating Tasks Using PowerShell Scripting

9. On the Predefined Rules page, click Next to accept the new rules.

10. On the Action page, select Allow the Connection, and then click Finish. Allow the

Connection is the default selection.

11. Repeat steps 6 through 10 and create inbound rules for the following predefined

rule types:

. Remote Service Management

. Windows Firewall Remote Management

Background Jobs

Another new feature that was introduced in PowerShell 2.0 is the ability to use back-

ground jobs. By definition, a background job is a command that is executed asynchro-

nously without interacting with the current PowerShell session. However, once the

background job has finished execution, the results from these jobs can then be retrieved

and manipulated based on the task at hand. In other words, by using a background job,

you can complete automation tasks that take an extended period of time to run without

impacting the usability of your PowerShell session.

By default, background jobs can be executed on the local computer. But, background jobs

can also be used in conjunction with remoting to execute jobs on a remote machine.

ptg

NOTE

To use background jobs (local or remote), PowerShell must be configured for remoting.

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:

. A Command pane for running interactive commands.

. A Script pane for writing, editing, and running scripts. You can run the entire script

or selected lines from the script.

. A scrollable Output pane that displays a transcript of commands from the Command

and Script panes and their results.

. Up to eight independent PowerShell execution environments in the same window,

each with its own Command, Script, and Output panes.

. Multiline editing in the Command pane, which lets you paste multiple lines of code,

run them, and then recall them as a unit.

. A built-in debugger for debugging commands, functions, and scripts.

Understanding the PowerShell Basics

721

21

FIGURE 21.1

The PowerShell ISE.

. Customizable features that let you adjust the colors, font, and layout.

ptg

. A scriptable object model that lets you further customize and extend the

PowerShell ISE.

. Line and column numbers, keyboard shortcuts, tab completion, context-sensitive

Help, and Unicode support.

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:

. Windows XP and later versions of Windows

. Microsoft .NET Framework 3.5 with Service Pack 1

NOTE

Being a GUI-based application, the PowerShell ISE does not work on Server Core instal-

lations of Windows Server.

722

CHAPTER 21

Automating Tasks Using PowerShell Scripting

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 vari-

ables 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 recom-

mended, as shown in this example:

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

PS C:\> $Stopped

Status Name DisplayName

------ ---- -----------

Stopped ALG Application Layer Gateway Service

Stopped Appinfo Application Information

ptg

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.

Understanding the PowerShell Basics

723

Alias cmdlets

In PowerShell, several alias cmdlets enable an administrator to define new aliases, export

21

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

CommandType Name Definition

----------- ---- ----------

Cmdlet Export-Alias Export-Alias [-Path]

Cmdlet Get-Alias Get-Alias [[-Name]

Cmdlet Import-Alias Import-Alias [-Path]

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

ptg

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 recom-

mended. 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

Other books

Blood Pact (McGarvey) by Hagberg, David
A Scottish Love by Karen Ranney
Ghost Keeper by Jonathan Moeller
Mad for the Billionaire by Charlotte DeCorte
Viper by Jessica Coulter Smith
Hard Candy by Andrew Vachss
A Witness to Life (Ashland, 2) by Terence M. Green
The Postcard Killers by James Patterson, Liza Marklund
Bad Blood by Mary Monroe