Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

return value from a scriptblock

$
0
0

Hi,
Is it possible to get return values from a scriptblock? I am running a parallel process to process around 10000 commands through the scriptblock. The array variable $Commands contains 10000 commands. I want to get the value of $exitcode and $standardoutput from each run. I want to collect all results and finally add results into an array so I can write the whole results in a logfile. Can anyone please help?


My code:
----

## Run job in parallel

$MaxThreads = 4
$SleepTimer = 1000

ForEach ($Command in $Commands)
{
    While (@(Get-Job -state running).count -ge $MaxThreads)
{      
    Start-Sleep -Milliseconds $SleepTimer
    }

    Start-Job -scriptblock {
   $objProcess = New-Object System.Diagnostics.Process
   $objProcess.StartInfo = New-Object System.Diagnostics.ProcessStartInfo
   $objProcess.StartInfo.FileName = "C:\Program Files (x86)\SPSS\perfcalc.exe"
   $objProcess.StartInfo.Arguments = $($args[0])
   $objProcess.StartInfo.UseShellExecute = $shell
   $objProcess.StartInfo.WindowStyle = 1
   $objProcess.StartInfo.RedirectStandardOutput = $true
   $null = $objProcess.Start()
   $objProcess.WaitForExit()
   $exitcode = $objProcess.ExitCode
   $standardoutput = $objProcess.StandardOutput.ReadToEnd()
   $objProcess.Dispose()

    } -ArgumentList $Command -Name "$($Command)job" | Out-Null
}

While (@(Get-Job -State Running).count -gt 0)
{
    Start-Sleep -Milliseconds $SleepTimer
}

ForEach($Job in Get-Job)
{
    Receive-Job -Job $Job
    Remove-job -Force $Job
}

-----

I took the code idea from here:

http://pwndizzle.blogspot.se/2013/12/powershell-threading.html


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>