Start Job - PowerShell


Overview

Start-Job initiates a new background job in a PowerShell session and returns an object representing the job. Background jobs allow you to execute long-running or computationally intensive tasks without blocking the console.

Syntax

Start-Job [-Name] <string> [-ScriptBlock] <scriptblock> [-ArgumentList] <object[]> [-File] <string> [-FileType] <string> [-FilePath] <string> [-WhatIf] [-Confirm] [-ThrottleLimit] <int> [-Session] <PSSession> [-Culture] <string> [-UICulture] <string> [-Location] <string>

Options/Flags

  • -Name: Specifies a unique name for the job.
  • -ScriptBlock: The script block to execute as the job.
  • -ArgumentList: An array of arguments to pass to the script block.
  • -File: Path to a script file to execute as the job.
  • -FileType: Type of script file specified in -File. Defaults to “PowerShell”.
  • -FilePath: Path to the directory where the script file is located.
  • -WhatIf: Displays what would happen without actually starting the job.
  • -Confirm: Prompts for confirmation before starting the job.
  • -ThrottleLimit: Sets the maximum number of concurrent jobs allowed.
  • -Session: Runs the job in the specified PowerShell session.
  • -Culture: Culture info to use for the job.
  • -UICulture: UI culture info to use for the job.
  • -Location: Specifies a location to run the job on.

Examples

Simple Job Execution:

Start-Job -ScriptBlock { Write-Host "Hello, background job!" }

Job with Arguments:

$args = @("Argument1", "Argument2")
Start-Job -ScriptBlock { Param($arg1, $arg2); Write-Host $arg1 " - " $arg2 } -ArgumentList $args

Job from a Script File:

Start-Job -File "C:\path\to\script.ps1"

Common Issues

  • Job not starting: Ensure the script block or script file is valid and executable.
  • Limited concurrency: Adjust the -ThrottleLimit option if multiple jobs are exceeding the limit.
  • Access to session variables: Remote jobs in different sessions cannot access variables from the originating session.

Integration

Pipeline: Start-Job can be used with the ForEach-Object cmdlet to process items in parallel:

Get-Process | ForEach-Object -Parallel { Start-Job -ScriptBlock { Param($p) Write-Host $p.ProcessName } -ArgumentList $p }

Remote Execution: Use the -Session option to start jobs on remote computers:

$session = New-PSSession -ComputerName "RemoteComputer"
Start-Job -Session $session -ScriptBlock { Write-Host "Hello from remote!" }
  • Get-Job: Gets information about running or completed jobs.
  • Receive-Job: Receives output from completed jobs.
  • Stop-Job: Stops a running job.
  • Wait-Job: Waits for a running job to complete.