YorSubs
YorSubs

Reputation: 4050

PowerShell Jobs complete but do not create output

I'm trying to get Jobs to work and hitting an issue with them again. EDIT: Realised that I need to change each of the variables inside the Job ScriptBlocks to include "using", so $using:temp_cpu, $using:temp_cpu_cores, $using:temp_cpu_logical

Even with the using fix, the output below still randomly results in empty output, even though I am waiting for the output files to a) exist, and b) be non-zero size, but about 1 in 3 runs of the below results in empty output.

function test {
    $temp_cpu = "$($env:TEMP)\ps_temp_cpu.txt"
    $temp_cpu_cores = "$($env:TEMP)\ps_temp_cpu_cores.txt"
    $temp_cpu_logical = "$($env:TEMP)\ps_temp_cpu_logical.txt"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    $job_cpu         = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).Name > $using:temp_cpu }
    $job_cpu_cores   = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).NumberOfCores > $using:temp_cpu_cores }
    $job_cpu_logical = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).NumberOfLogicalProcessors > $using:temp_cpu_logical }
    Wait-Job $job_cpu, $job_cpu_cores, $job_cpu_logical
    while (!(Test-Path $temp_cpu)) { while ((Get-Item $temp_cpu -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    while (!(Test-Path $temp_cpu_cores)) { while ((Get-Item $temp_cpu_cores -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    while (!(Test-Path $temp_cpu_logical)) { while ((Get-Item $temp_cpu_logical -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }

    "CPU:               $(cat $temp_cpu)"
    "CPU Cores:         $(cat $temp_cpu_cores)"
    "CPU Logical:       $(cat $temp_cpu_logical)"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
}

Upvotes: 0

Views: 93

Answers (1)

Guenther Schmitz
Guenther Schmitz

Reputation: 1999

try this:

$job_cpu = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).Name }
Wait-Job $job_cpu
Receive-Job -Job $job_cpu -OutVariable job_cpu_output
$job_cpu_output > $temp_cpu

Upvotes: 1

Related Questions