You are on page 1of 44

Module 7

Background Jobs and


Remote Administration

Module Overview
After completing this module, you will be able to:
Start and manage background jobs

Receive results from background jobs


Integrate background jobs into other tasks and processes
Manage remote computers by using one-to-one remoting

Execute commands on multiple remote computers


Import remote commands into the local shell
Use implicit remoting to run commands

that are located on a remote computer

Lesson 1: Working with Background Jobs


After completing Lesson 1, you will be able to:
Explain how background jobs are executed in the shell

Create a new background job for WMI operations


Create a new background job that executes commands on the

local computer

Display current job status

Retrieve the results from a job and work with those results in the

pipeline

Retrieve the results from a job and leave the results cached in

memory

Retrieve the properties of a job


Remove a completed job
Wait for a job to complete
Stop a job that has hung or that will not complete

Interactive vs. Background


Most PowerShell commands complete interactively, also

known as synchronously

The first command must complete before the next command


can start

This works well when subsequent commands rely on data from


previously-run commands

Sometimes you want a command or series of commands

to run in the background

Background jobs move processing to the background

Commands execute, but the shell is freed for other activities

Results from background jobs are saved in memory as a

job object

Job object data can be retrieved from completed jobs

Job object data can be used for other background or


interactive commands

Background WMI
The Get-WmiObject cmdlet

Often requires a very long time to run. This is particularly the


case when Get-WmiObject is run against multiple remote
computers at once.

Has an AsJob parameter, which runs its query as a


background job.
Get-WmiObject computer (gc names.txt) class
CIM_DataFile AsJob

Rather than waiting for WMI to complete, the

AsJob parameter instead places a job object in the


pipeline and begins executing in the background.

The AsJob parameter can be found in other cmdlets,

some of which will be discussed in this module.

Managing Jobs
Four important cmdlets are used to manage the list of

running jobs

Get-Job

Remove-Job

Wait-Job

Stop-Job

These management cmdlets should feel similar to the


command line tools youve used in the past for at jobs
and scheduled tasks

Demonstration: WMI Jobs


Learn to start jobs by using Get-WmiObject

Job Output
At some point, you need to gather the data from a

background job. That data is contained within the jobs Job


Object.

The Receive-Job cmdlet

Obtains the results from a background job in memory.

Receive-Job id 2 | Sort State | Where { $_.State ne


"Stopped" }
It is also useful to assign the results of Receive-Job to a

variable.

$results = Receive-Job id 2
Retrieving the output of a job also removes that output

from the jobs memory cache. Use the keep parameter to


retain this data for later use.

Demonstration: Working with Job Output


Learn how to work with job output

Managing the Job List


The shell retains information about in-progress and

completed jobs, even after youve received job results.

You will need to clean up the job list from time to time,

using the Remove-Job cmdlet. There are multiple


approaches you can use:

By ID

By Instance ID

By name

By state

By piping jobs to Remove-Job

Remove-Job id 1
Remove-Job name Job1
Get-Job | Where { $_.Name like "AD*" } | Remove-Job

Demonstration: Removing Jobs


Learn how to manage the job list

Other Commands as Jobs


As mentioned before, some cmdlets other than Get-

WmiObject can be converted to jobs using the AsJob


parameter

Alternatively, any command can become a background job

by using the Start-Job cmdlet

Start-Job executes a script block in the background

Start-Job can leverage alternate credentials

Start-Job -scriptblock {Get-Process}

The Invoke-Command cmdlet can also run jobs in the

background, but only against remote computers

Invoke-Command will be covered in this modules next lesson

Demonstration: Local Commands As Jobs


Learn how to run local commands as background jobs

Lab A: Working with Background Jobs


Exercise 1: Using Background Jobs with WMI
Exercise 2: Using Background Jobs for Local Computers

Exercise 3: Receiving the Results from a Completed Job


Exercise 4: Removing a Completed Job
Exercise 5: Waiting for a Background Job to Complete
Exercise 6: Stopping a Background Job Before It Completes
Exercise 7: Working with the Properties of a Job

Logon information
Virtual machine

LON-DC1

LON-SVR1

Logon user name

Contoso\Administrator ContosoAdministrator

Password

Pa$$w0rd

Pa$$w0rd

Estimated time: 30 minutes

Lab Scenario
You are a system administrator who has several scripts

already developed.

Some of the scripts can take anywhere from a few seconds

to several minutes to complete. You would waste a lot of


productive time if you ran the scripts one-by-one and
waited for each to finish.

To save time, you are going to use background jobs to run

all the scripts synchronously, and be able to control


everything from one PowerShell console.

Lab Review
You have started a PowerShell console and have started a

couple of background jobs. What happens to the


background jobs if they are still running and the main
console is closed?

If you have two or more PowerShell consoles open, and

start a background job in one console, can you access the


job from the other console?

Lesson 2: Using Windows PowerShell Remoting


After completing this lesson, you will be able to:
Explain the architecture of Windows Remote Management (WinRM)
Configure WinRM on the local computer
Configure WinRM in a domain environment
Configure Windows Remote Shell in a domain environment
Open, use, and close an interactive remote shell session

Invoke a command that executes on one or more remote computer


Work with the results of commands that executed on multiple computers
Invoke a command that executes on multiple computers and that runs as

a background job

Receive the results of a background job that includes commands that

executed on remote computers

Create, manage, and remove reusable objects that represent connections

to remote computers

Use implicit remoting to execute commands that are installed on a

remote computer

Why Manage Remotely?


Now that your knowledge of command-line management is

growing, it no longer makes sense to perform many tasks


at the computers console

Managing at the console is a poor management practice

Managing at the console consumes excess on-system


resources, which can impact running processes

Managing at the console takes extra steps, which slows down


your ability to solve problems and enact change

Managing at the console is not repeatable

Managing at the console has a greater possibility of error,


especially when repeating complicated tasks

Microsoft has gradually added remote management

capabilities to its administrative tools

With PowerShell, nearly any command can be executed on

one or more remote computers

Many Forms of Remoting


The actual process of remote administration with

PowerShell can involve different approaches:

Cmdlets with a computerName parameter dont use


PowerShell remoting. They use RPC calls, which are not
firewall friendly.

Some cmdlets are designed to work with a remote computer


by default. These cmdlets use protocols related to their
specific technology.

Windows PowerShell Remoting involves connecting to a


remote computer, and then running a command locally on that
computer.

Windows PowerShell Remoting


The purpose of PowerShell Remoting is to

Connect to a remote computer

Run one or more commands on that computer

Bring those results back to your computer

The goals of PowerShell Remoting are

Single seat administration

Batch administration

Lightweight administration

The three ways to use PowerShell Remoting are

1-to-1 Remoting

1-to-Many (or Fan-Out) Remoting

Many-to-1 (or Fan-In) Remoting

WinRM
PowerShell Remoting rides on top of the Windows Remote

Management Service (WinRM).

WinRM is a Microsoft implementation of Web Services for


Management (WS-MAN).

Unlike RPC, WinRM uses a single, definable port, making it


easier to pass through firewalls.

WinRM can use TLS/SSL to encrypt data being passed through


the network.

WinRM uses Active Directorys Kerberos for authentication.

WinRM is disabled by default on all computers. It can be


enabled locally on a single computer or via Group Policy.

WinRM v2 uses 5985/TCP as its default port for

communication. This is different from WinRM v1, which


used 80/TCP.

How WinRM Works


WinRM operates as a Windows service

Once enabled, that service listens on the assigned port for


external requests

WinRM examines inbound requests to determine the


application for which the request is meant

Applications must register an endpoint with WinRM, telling the


service that the application is available and capable of
processing WinRM requests

Kerberos (for authentication) and TLS/SSL (for encryption) are


used during communication

You must specifically register PowerShell as an endpoint to

receive remoting requests, for security purposes


Enable-PSRemoting

Discussion: Enabling WinRM


Are there any challenges to implementing WinRM in your

environment?

Network challenges?

Security challenges?

Configuration control challenges?

Corporate policy or compliance challenges?

Remote Shell
The Enable-PSRemoting cmdlet

Enables WinRM

Starts the WinRM service

Sets the WinRM service to start automatically

Modifies the Windows Firewall configuration to permit


incoming WinRM connections

Registers both the 64- and 32-bit versions of Windows


PowerShell as WinRM endpoints as appropriate

Enable-PSRemoting has an impact level of high, so you will

be prompted to confirm your choice to allow the cmdlet to


run

Alternative: Group Policy!

Demonstration: Enabling Remote Shell


Learn how to enable Remoting

1-to-1 Shell
The 1-to-1 shell creates a remote command-line prompt

inside your local PowerShell session

Similar to Telnet, SSH, or PSExec \\computerName cmd

Running commands in the remote command-line prompt


executes those commands on the remote system
Enter-PSSession comp server-r2

To exit the remote session, use


Exit-PSSession
Remember, all 1-to-1 shell commands execute locally on

the remote computer

Demonstration: Using 1-to-1 Remoting


Learn to use 1-to-1 Remoting

1-to-Many Remoting
1-to-Many Remoting is useful when you need to execute

the same command on multiple computers

With 1-to-Many Remoting

You submit a set of commands


to a list of computers

Each computer executes the


set of commands

Then, each computer returns


its result back to your computer

Invoke-Command scriptblock { Dir c:\demo }


computerName Server1,Server2,Server3
Invoke-Command runs synchronously, which means you

must wait for it to finish before running more commands

Pipeline Binding
Recall that some cmdlets bind their pipeline input

ByPropertyName. This means that property names must


match.

Problem: The computerName parameter of Invoke-Command


binds ByPropertyName, but some cmdlets produce objects
that use the Name property instead.

Solution: Create custom objects to change the property name.

Get-ADComputer filter * |
Select
@{Label='ComputerName';Expression={$_.Name}} |
Get-Service name *

Working with Results


Recall: PowerShell cmdlets return objects as their output.
This poses a problem

Software objects cannot be transmitted over the network.

To compensate, WinRM serializes those objects into XML for


transfer, then deserializes them back into objects at your
computer.

This changes how remote computer results data look,


reverting them to text-based snapshots of those objects. It
also strips away the methods associated with the object.

To maintain some of the object-oriented flexibility,

PowerShell adds a few additional properties to deserialized


objects.

PSComputerName enables you to sort and group objects.


Invoke-Command script { Get-Service } computer
Server1,Server2 | Sort PSComputerName | FormatTable groupby PSComputerName

Multi-Computer Jobs
Jobs that span across multiple computers create top-level

jobs, along with child jobs

Top-level jobs represent the multi-computer job as a whole

Child jobs represent the job on each remote computer

To view the names of child jobs


Get-Job -id 1 | Select childjobs
To retrieve child jobs
Get-Job -name job2
To retrieve child job results
Receive-Job name Job2 keep

Keep Workloads Remote


As a best practice, try to execute as much processing on

remote systems as possible

This practice is computationally less expensive

Example: Avoid this


Invoke-Command script { Get-Service } computer Server1 |
Where { $_.Status eq "Running"} |
Sort Name |
Export-CSV c:\services.csv
Do this instead
Invoke-Command script {
Get-Service |
Where { $_.Status eq "Running" } |
Sort Name
} | Export-CSV c:\services.csv

Demonstration: Using 1-to-Many Remoting


Learn to use 1-to-Many Remoting

Restricted Runspaces
Recall: Restricted runspaces are created by developers to

limit administrative capabilities on that server

A hosted Exchange provider may limit your PowerShell


Remoting capabilities to only certain portions or areas of the
Exchange configuration

PowerShell restricted runspaces provide this capability

Restricted runspaces can

Remove certain parameters from a cmdlet, or replace


parameters with fixed values

Add new cmdlets, remove cmdlets

Add, remove, or change parameters

Be aware that some cmdlets may not behave exactly as

expected if restricted runspaces have been implemented

Disadvantages of Specifying Connection Details


Having to specify connection details over and over for

many different connections is repetitive and can cause


errors

PowerShell offers a way to create and reuse connections


The New-PSSession cmdlet

Uses parameters that are similar to Enter-PSSession and


Invoke-Command

Creates a persistent session object, which can be stored in a


variable for later use

Maintains this persistent session object for as long as the shell


window remains open
$sessions = New-PSSession computer Srv1,Srv2,Srv3
Invoke-Command script { Get-Service } session
$sessions
$sessions = New-PSSession computer Srv1,Srv2,Srv3
Enter-PSSession session $sessions[1]

Best Practices
Some best practices

Always use Start-Job to start a local background job

Never use Invoke-Command andAsJob to start a local


background job

Using Invoke-Command to start a local job creates a

loopback situation

The local WinRM service communicates with itself over the


network

This creates some tricky security situations

Session Management
Sessions require on-system resources to remain open

They consume memory, processor, and networking overhead

Its a good idea to close sessions when youre finished with


them

The Remove-PSSession cmdlet

Closes sessions that are no longer necessary

Can use variables to close individual sessions or sets of


sessions
$sessions | Remove-PSSession
Get-PSSession | Remove-PSSession

Demonstration: Session Management


Learn to manage sessions

Implicit Remoting
The topic of implicit remoting was first introduced in

Module 5.

Recall: Some cmdlets will not run on some operating systems.


For example, the ActiveDirectory cmdlet will not run on
Windows XP. Implicit remoting enables cmdlets from a morecapable computer to be used on less-capable computer.

Three basic steps:

Use New-PSSession to establish a session from the Windows


XP computer to the domain controller that contains the
ActiveDirectory module.

Invoke a command on the domain controller to load the


ActiveDirectory module.

Use the Import-PSSession cmdlet to import the remote


commands to the Windows XP computer. Specify that only
commands whose nouns start with AD be exported, which
ensures that only the Active Directory cmdlets are included in
the export.

Demonstration: Implicit Remoting


Learn to use implicit remoting

Lab B: Using Windows PowerShell Remoting


Exercise 1: Interactive Remoting
Exercise 2: Fan-Out Remoting

Exercise 3: Fan-Out Remoting Using Background Jobs


Exercise 4: Saving Information from Background Jobs

Logon information
Virtual machine

LON-DC1

LON-SVR1

LON-SVR2

Logon user name

Contoso\Administrator

Contoso\Administrator

Contoso\Administrator

Password

Pa$$w0rd

Pa$$w0rd

Pa$$w0rd

Estimated time: 45 minutes

Lab Scenario
You are a system administrator and often need to run

commands on remote computers.

You could ask each user to run the commands themselves,

but you prefer to have control to run the commands


yourself.

You have heard about being able to run remote commands

using WMI, and know that your company also has a


desktop management system that may be able to run
these commands, but you would rather be in complete
control of the commands yourself.

Furthermore, your company uses host firewalls and you

understand that they can cause issues with using WMI. So


youve decided to implement PowerShell remoting
throughout your organization.

Lab Review
Is there any limit to the number of remote sessions that

can be run?

If I use Invoke-Command from one console and start it as

a background job, can other consoles on the same server


also see the background jobs and access their information
directly?

Module Review and Takeaways


What is the primary difference between Start-Job and

Invoke-Command (used with its AsJob parameter)?

Will implicit remoting work if the remote computer does

not have WinRM enabled?

What command would disable Remoting on the local

computer?

You might also like