LOGO

Geek School: PowerShell Jobs - Learn to Use Them

April 8, 2013
Geek School: PowerShell Jobs - Learn to Use Them

PowerShell Job Types: An Overview

PowerShell offers four distinct job types for managing tasks: Background Jobs, Remote Jobs, WMI Jobs, and Scheduled Jobs. This article will explore each of these, detailing their functionality and practical applications.

Understanding PowerShell Jobs

Jobs in PowerShell allow you to execute commands asynchronously. This means that PowerShell doesn't wait for a command to finish before moving on to the next one, improving efficiency and responsiveness.

Different job types cater to various needs, from running tasks in the background on the local machine to executing commands on remote systems or leveraging Windows Management Instrumentation (WMI).

Background Jobs

Background Jobs run commands asynchronously on the local computer. They are ideal for tasks that might take a long time to complete without blocking the PowerShell session.

These jobs operate within the same process space as the parent PowerShell session, offering a relatively lightweight approach to parallel execution.

Remote Jobs

Remote Jobs enable the execution of commands on one or more remote computers. This is particularly useful for system administration tasks that need to be performed across a network.

Utilizing PowerShell remoting, these jobs allow you to manage remote systems as if they were local, streamlining administrative processes.

WMI Jobs

WMI Jobs leverage Windows Management Instrumentation to execute asynchronous operations. WMI provides a standardized way to manage and monitor systems, making WMI Jobs a powerful tool for system administrators.

These jobs are particularly effective when dealing with tasks that involve interacting with WMI providers and managing system components.

Scheduled Jobs

Scheduled Jobs allow you to run commands at specific times or intervals. This is similar to the Windows Task Scheduler, but managed directly through PowerShell.

Scheduled Jobs are ideal for automating routine tasks, such as backups, maintenance scripts, or report generation.

Further Learning

For a more comprehensive understanding of PowerShell, be sure to review these preceding articles in the series:

  • Learn How to Automate Windows with PowerShell
  • Learning to Use Cmdlets in PowerShell
  • Learning How to Use Objects in PowerShell
  • Learning Formatting, Filtering and Comparing in PowerShell
  • Learn to Use Remoting in PowerShell
  • Using PowerShell to Get Computer Information
  • Working with Collections in PowerShell

Additional articles exploring these concepts will be released throughout the week, so stay tuned for more insights into the capabilities of PowerShell.

Background Jobs in PowerShell

Previously, all PowerShell commands executed synchronously, meaning the shell remained occupied until each command completed. This limitation is addressed through the use of background jobs. Initiating a background job is achieved by submitting a script block to the Start-Job cmdlet.

Start-Job –Name GetFileList –Scriptblock {Get-ChildItem C:\ –Recurse}

This allows for continued interaction within the PowerShell session while the specified script block runs independently in the background.

geek-school-learn-how-to-use-jobs-in-powershell-1.jpg

Upon launching a new job, PowerShell generates a corresponding job object to represent it. A comprehensive list of all active jobs can be retrieved at any time using the Get-Job cmdlet.

geek-school-learn-how-to-use-jobs-in-powershell-2.jpg

These job objects provide insights into the status of each job. For instance, the screenshot illustrates a BackgroundJob named GetFileList, currently executing and already producing output.

Stopping Background Jobs

Should a job exceed an acceptable runtime, it can be terminated by piping its output from Get-Job to the Stop-Job cmdlet.

Get-Job –Name GetFileList | Stop-Job

Even after termination, any data the job had processed up to that point remains accessible.

geek-school-learn-how-to-use-jobs-in-powershell-3.jpg

However, a crucial point to remember is that PowerShell automatically deletes job results once they are retrieved. To prevent this deletion and preserve the output, the –Keep switch parameter must be used with the Receive-Job cmdlet.

Get-Job –Name GetFileList | Receive-Job –Keep

geek-school-learn-how-to-use-jobs-in-powershell-4.jpg

Cleaning Up Jobs

Once a job is no longer needed, it's considered best practice to remove it. This is accomplished by piping the job object to the Remove-Job cmdlet.

Get-Job –Name GetFileList | Remove-Job

Removing the job ensures it will no longer appear in the list returned by Get-Job.

geek-school-learn-how-to-use-jobs-in-powershell-5.jpg

Proper job management, including removal, contributes to a cleaner and more efficient PowerShell environment.

geek-school-learn-how-to-use-jobs-in-powershell-6.jpg

By utilizing background jobs, PowerShell allows for parallel execution of tasks, enhancing overall productivity and responsiveness.

Executing PowerShell Commands Remotely with Jobs

Previously, we explored utilizing remoting to execute PowerShell commands on distant machines via Invoke-Command. However, did you know Invoke-Command can also initiate a remote job operating in the background?

To accomplish this, simply append the –AsJob parameter to your command:

Invoke-Command -ComputerName Flash,Viper -Credential administrator -ScriptBlock {gci} –AsJob

This is a straightforward command and should have completed execution already. Let's now examine the status of our jobs.

Interestingly, it appears the job has failed. This leads to a crucial point regarding jobs in PowerShell.

When a new job is created, regardless of its type, PowerShell generates a parent job alongside a child job for each targeted computer. The Get-Job cmdlet, by default, only displays the parent jobs.

The state property reflects the worst-case scenario; even if the command only fails on a single machine out of many, the parent job's status will indicate failure. To view the individual child jobs, the IncludeChildJob parameter is necessary.

Upon closer inspection, it becomes clear that the job only encountered an error on one computer.

This brings us to another important consideration. When attempting to retrieve the job results, specifying the parent job's name or ID will return data from all child jobs.

If an error occurred within one of the child jobs, the output will include error messages.

There are two methods to circumvent this issue. First, if you know the specific computers for which you require results, you can utilize the ComputerName parameter with the Receive-Job cmdlet.

Get-Job –Id 3 | Receive-Job –Keep –ComputerName Viper

Alternatively, you can obtain results from a specific child job by using its unique job ID.

Get-Job -Id 3 –IncludeChildJob

Get-Job -Id 5 | Receive-Job –Keep

WMI Jobs

WMI Jobs function similarly to Remote Jobs, necessitating only the inclusion of the –AsJob parameter when utilizing the Get-WmiObject cmdlet.

This parameter enables the execution of WMI operations as background jobs within PowerShell.

However, it’s important to note that WMI Jobs share the same potential issues and limitations previously discussed concerning Remote Jobs.

Similarities to Remote Jobs

The core functionality of WMI Jobs mirrors that of Remote Jobs. Both leverage asynchronous processing to improve script efficiency.

By employing the –AsJob parameter, PowerShell can continue executing subsequent commands while the WMI query or operation runs in the background.

Potential Issues

Like Remote Jobs, WMI Jobs can encounter challenges related to session management and error handling.

Careful consideration must be given to these aspects to ensure reliable and predictable job execution.

Specifically, the same caveats regarding proper error trapping and result retrieval apply to both job types.

Understanding these potential pitfalls is crucial for successful implementation.

It is essential to implement robust error handling to manage unexpected outcomes.

Properly retrieving and processing the job results is also vital for accurate data analysis.

Scheduled Jobs

Previously examined job types were non-persistent, existing only within the current session. This means initiating a job and then querying its status from a separate PowerShell console will yield no results. However, returning to the original console where the job was launched will allow you to monitor its progress. Scheduled Jobs differ significantly, as they maintain persistence.

Essentially, a Scheduled Job defines a script block executed according to a predetermined schedule. Historically, the Windows Task Scheduler fulfilled a similar function, and indeed, remains the underlying mechanism. The following command demonstrates the creation of a new Scheduled Job:

Register-ScheduledJob -Name GetEventLogs -ScriptBlock {Get-EventLog -LogName Security -Newest 100} -Trigger (New-JobTrigger -Daily -At 5pm) -ScheduledJobOption (New-ScheduledJobOption -RunElevated)

The command incorporates several components, requiring detailed explanation.

  • Initially, the Scheduled Job is assigned the name "GetEventLogs".
  • Subsequently, the command specifies that upon triggering, the script block's contents will be executed. This particular script block retrieves the 100 most recent entries from the Security event log.
  • A trigger is then defined. The Trigger parameter accepts a trigger object; therefore, a parenthetical command constructs a daily trigger set to activate at 5:00 PM.
  • Accessing the event log necessitates administrative privileges. This is achieved by creating a ScheduledJobOption object and passing it to the ScheduledJobOption parameter.

This ensures the job runs with elevated permissions.

geek-school-learn-how-to-use-jobs-in-powershell-16.jpg

Due to the distinct nature of this job type, a different command is required to list all scheduled jobs on a system.

Get-ScheduledJob

This command retrieves a comprehensive list of all configured scheduled jobs.

geek-school-learn-how-to-use-jobs-in-powershell-17.jpg

That concludes the explanation of Scheduled Jobs in PowerShell.

#PowerShell#Jobs#PowerShell Jobs#Geek School#scripting#automation