When I execute a simple statement locally
$path = 'C:\Windows\System32\WindowsPowerShell\v1.0'
gci $path
I see the response immediately. But when I execute it as job on my local machine
$start = get-date
$path = 'C:\Windows\System32\WindowsPowerShell\v1.0'
$cmd = [scriptblock]::Create("gci $path")
$jnr1 = Invoke-Command -computer localhost -ScriptBlock $cmd -asJob
Wait-Job $jnr1
Receive-job $jnr1
$end = Get-date
($end - $start).totalseconds
I have to wait 55 seconds. From my unix experience a decade ago. I would expect background jobs to run nearly as fast as foreground jobs.
Are there ways to speed up the execution of PowerShell background jobs?
This shorter command does the same thing:
Measure-Command {Start-Job -Command {gci C:\Windows\System32\WindowsPowerShell\v1.0} | Wait-Job | Receive-Job}
On Win8 beta w/ PSv3 it was fast for me ~3 seconds, on WinXp w/ PSv2 it was ~15-30 seconds.
Background jobs were introduced w/ PsV2. They've had time to optimize since v2 and PowerShell now uses the DLR in v3 now so that might explain the differences in performance.
It has to spin up another powershell process with the command text, run the command, send back the serialized results and tear down the process.
To find out what its doing I ran procmon while the above command was running and a majority of the time powershell.exe was reading networking and COM related reg keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With