Um momento
0xE0Lesson 15 of 17

Jobs, scheduling and remoting

Run work in the background with jobs, schedule scripts, and manage other machines with remoting.

24 min 7-question quiz 1 code exercise
By the end of this lesson you can
  • Start, wait for and collect background jobs, and pass them arguments
  • Choose between jobs, thread jobs and ForEach-Object -Parallel
  • Run commands on other computers with Invoke-Command and PowerShell remoting

Some work is slow - pinging twenty enclosure sensors, copying big backups. Background jobs run it while you carry on:

CmdletDoes
Start-Job { ... }runs a script block in a new background PowerShell process
Get-Joblists jobs and their State (Running, Completed, Failed...)
Wait-Jobwaits until jobs finish
Receive-Jobcollects their output
Remove-Jobcleans them up

A job runs in a separate process, so it can’t see your variables. Pass values in with -ArgumentList (they arrive as $args or the job’s param()), or refer to them as $using:name.

jobs.ps1
1$sensors = 'volcano', 'lagoon', 'tower'
2$jobs = foreach ($sensor in $sensors) {
3  Start-Job -ArgumentList $sensor -ScriptBlock {
4    param($name)
5    "$name sensor: $($name.Length * 7) degrees"
6  }
7}
8$jobs | Wait-Job | Receive-Job | Sort-Object
9$failing = Start-Job { throw 'sensor offline' }
10$failing | Wait-Job | Out-Null
11"state: $($failing.State)"
12Get-Job | Remove-Job
Output
lagoon sensor: 42 degrees
tower sensor: 35 degrees
volcano sensor: 49 degrees
state: Failed

Starting a whole process per job is heavy. Two lighter options run in threads inside your session:

  • Start-ThreadJob - same commands as Start-Job, much faster to start (built into PowerShell 7).
  • ForEach-Object -Parallel (PowerShell 7) - run a script block for many items at once, up to -ThrottleLimit at a time:
$sensors | ForEach-Object -Parallel {
  Test-Connection "$_.sensors.emberfall" -Count 1 -Quiet
} -ThrottleLimit 10

Scheduling

To run a script every night, hand it to the operating system’s scheduler:

  • Windows Task Scheduler: Register-ScheduledTask with a trigger (New-ScheduledTaskTrigger -Daily -At 3am) and an action (New-ScheduledTaskAction -Execute pwsh -Argument '-File C:\Scripts\Feed.ps1').
  • Linux and macOS: a cron line such as 0 3 * * * pwsh -File /opt/scripts/feed.ps1.

Scheduled scripts run without you watching, so use everything from the last two lessons: strict mode, -ErrorAction Stop with try/catch, a transcript or log, and a non-zero exit code on failure.

Remoting: one console, many machines

PowerShell remoting runs commands on other computers and sends back objects, not text:

1# Run one command on several servers at once
2Invoke-Command -ComputerName castle-01, castle-02 -ScriptBlock { Get-Service sshd }
3
4# An interactive session on a remote machine (exit with Exit-PSSession)
5Enter-PSSession -ComputerName castle-01
6
7# A reusable connection for several commands
8$session = New-PSSession -ComputerName castle-01
9Invoke-Command -Session $session { Get-Volume }

On Windows, remoting uses WinRM (Enable-PSRemoting turns it on). PowerShell 7 can also remote over SSH to Linux and macOS: Invoke-Command -HostName keeper@castle-03 { uname -a }. Results come back as deserialized objects - their properties are there, but methods that would act on the remote machine aren’t.

On Windows, CIM gets hardware and OS details from any machine: Get-CimInstance Win32_OperatingSystem -ComputerName castle-01 | Select-Object Caption, LastBootUpTime.

Key takeaways

  • Start-Job, Wait-Job, Receive-Job and Remove-Job run work in background processes; check .State for failures.

  • Pass values into jobs with -ArgumentList or $using:; Start-ThreadJob and ForEach-Object -Parallel are lighter.

  • Schedule scripts with Task Scheduler or cron - and make them log and fail loudly.

  • Invoke-Command and Enter-PSSession run commands remotely (WinRM, or SSH in PowerShell 7) and return objects.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write PowerShell scripts

Write a script in the editor and run it for real against sample input, which is piped into your script as $input. Scripts run on PowerShell 6.2 through Try It Online (tio.run), a free public service, so these exercises avoid PowerShell 7-only syntax; your script and test input are sent there.

Exercise 1

Sensor sweep

+25 XP

Each input line is an enclosure name. Start one background job per enclosure; each job outputs <name>: <reading> where the reading is the number of letters in the name times 7 (pretend that’s the temperature). If the name is broken, the job must throw instead.

Wait for all jobs, then print the successful readings sorted alphabetically, then failed: N, and clean up with Remove-Job.

  • Three enclosures
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: