Passing variables to a job
In order to pass a
variable to a
script block that is started with
start-job, the variable name needs to be prefixed with
using:.
$var=42
$scriptBlock = { add-content ~/variable-value "var=$var | using:var=$using:var" }
$var='changed'
start-job $scriptBlock
This script, when run, writes the following line into ~/variable-value:
var= | using:var=changed
Working directory for jobs ps-start-job-wd
A job's
working directory is set to
$home\Documents (Windows Powershell) or
$home (PowerShell Core).
After the job has finished, ~/current-directory can be inspected to determine the current directory of powershell jobs.
start-job { add-content ~/current-directory (get-location) }
PowerShell 7 finally comes with the new option -workingDirectory which allows to change the initial working directory for a background job.
Passing parameters to a scheduled cmdLet
The following command tries to use start-job to schedule a download of a resource and storing it to an aribitrary file, using the -outFile parameter:
start-job invoke-webRequest http://server.xyz/path/to/resource.pdf -outFile downloadedFile.pdf
However, this results in the error message Start-Job : Parameter set cannot be resolved using the specified named parameters. This is becouse start-job (rather than invoke-webRequest) tries to interprete the -outfile parameter.
In order to pass a parameter to a scheduled cmdLet, a
script block must be used:
start-job -scriptBlock { invoke-webRequest http://server.xyz/path/to/resource.pdf -outFile downloadedFile.pdf }
The -scriptBlock parameter is not necessary:
start-job { invoke-webRequest http://server.xyz/path/to/resource.pdf -outFile downloadedFile.pdf }
Of course, if using a script block to download a resource, absolute paths or the
working directory should be specified in order to download the file to a non-default location.
start-job { invoke-webRequest https//server.xyz/path/to/resource.pdf -outFile $using:pwd\downloadedFile.pdf }