Changing existing script to use runspaces

This topic contains 1 reply, has 1 voice, and was last updated by Profile photo of Глеб Боушев Глеб Боушев 8 months, 1 week ago.

  • Author
    Posts
  • #37204

    Hello, so I'm trying to get involved with all the runspaces hype... but I can't seem to figure it out 😉

    foreach ($file in $files) { 
        
        Write-Progress -Status "File Number $([array]::IndexOf($files, $file))" -Activity "Parsing Log Files" -PercentComplete (($([array]::IndexOf($files, $file)) / $files.Count) * 100)
    
    # I assume write-progress is useless when using runspaces?? #
    
        $SR = New-Object System.IO.StreamReader -ArgumentList $file.FullName
    
        try {
            while (($line = $SR.ReadLine()) -ne $null) {
                if ($line -match 'A002') {
                    $line -replace ' +',"," | Out-File $tempFile -Append
                }
            }
        }
        finally {
            $SR.Close()
        }
    }
    

    So I have this code at the moment and I'm trying to figure out a way to parallel this block of code. I tried using workflows foreach -parallel, but it wasn't really working properly, it was outputting a few lines every 30 seconds or so... So the whole idea is to parallel files parsing, not one file parsing ( I don't think that makes sense). I've seen a few examples of runspaces here and there, but I can't seem to figure out how to launch several runspaces and give each one a single file to chew on and how to return data from runspace. Out-file doesn't work for some reason. Stuff like this also doesn't

    $contents = new-object System.Collections.ArrayList
    foreach() {bla-bla-bla; [void] $contents.add($_.replace(somethingineedtodo))}
    $contents
    

    Any help appreciated, thanks!

  • #37209

    So to add to my question, I can't seem to get any string related stuff to work in runspaces, what does work right now:

    $ScriptBlock = {
        Param ($files)
        foreach ($file in $files) {
        $content += Get-Content $file.FullName -ReadCount 0
        $content
    }}
    
    $newPowerShell = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($files)
    $job = $newPowerShell.BeginInvoke()
    While (-Not $job.IsCompleted) {}
    $result += $newPowerShell.EndInvoke($job)
    

    If I try to add something like:

    $content | % {if ($line -match 'A002') {
            $something += $line -replace ' +',","}
    

    The result is empty. If I try to create new-object System.Collections.ArrayList the result is empty and I can't seem to find how do I debug this stuff. I know there are cmdlets like Debug-Runspace, but I see only one runspace when I do get-runspace... Any ideas? Thanks!

You must be logged in to reply to this topic.