Example Start-Job usage
Example of using Start-Job in your script.
Job file (\\path\job-example2.ps1)
This is the script that will be called multiple times. Wanted to illustrate calling a file with parameters. It's a trival example, but wanted to show different output in the job results.
param(
$runTask = $false,
$action
)
if($runTask){
$message = $action
switch($action){
"0"{
$message = $message + ":zero"
}
"1"{
$message = $message + ":one"
}
"2"{
$message = $message + ":two"
}
"3"{
$message = $message + ":three"
}
"4"{
$message = $message + ":four"
}
"5"{
$message = $message + ":five"
}
default{
$message = $message + ":don't know"
}
}
}else{
write-output "did not run"
}
Write-Output $message
Tasker file (\\path\job-example1.ps1)
This will create multiple jobs. Each job will be assigned a numeric iteration of the loop value as the name. We'll wait for all the jobs to finish and then get the output of each job using the name we assigned.
$scriptfile = $MyInvocation.MyCommand.Path
$scriptPath = split-path -parent $scriptfile
for($i=0;$i -le 5;$i++){
$arguments = @($true,"$i")
start-job -filepath "$scriptPath\job-example2.ps1" -ArgumentList $arguments -name $i
sleep -Seconds 1
}
do{
$state = get-job | ?{$_.state -eq 'Running'}
sleep -second 1
}while($state -ne $null)
for($i=0;$i -le 5;$i++){
receive-job -name $i
}
Expected output:
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
1 0 BackgroundJob Running True localhost param(...
3 1 BackgroundJob Running True localhost param(...
5 2 BackgroundJob Running True localhost param(...
7 3 BackgroundJob Running True localhost param(...
9 4 BackgroundJob Running True localhost param(...
11 5 BackgroundJob Running True localhost param(...
0:zero
1:one
2:two
3:three
4:four
5:five
No comments:
Post a Comment