0

I am using powershell to read a text file which has text in lines and display items. How do I use parallel foreach instead of foreach. I tried foreach and it works but foreach parallel syntax didnt work.

$lines = Get-Content myFile.txt | Where {$_ -notmatch '^\s+$'} 
Foreach ($Item in $lines) 
{
$Item 
}

MyFile.Txt

newyork is great 
seattle is cold
florida is hot

This is what I tried

$lines = Get-Content myFile.txt | Where {$_ -notmatch '^\s+$'} 
      ForEach -Parallel ($Item in $lines)
            {
            $Item
            }

Error: -parallel an be used only in workflow

1 Answer 1

1

To use the ForEach -parallel, use your code like this:

workflow myworkflow{
    $lines = Get-Content myFile.txt | Where {$_ -notmatch '^\s+$'} 
    ForEach -Parallel ($Item in $lines){
        sequence{
            $Item
        }
    }
}

Then, call you workflow: myworkflow.

Workflow are very useful, here you can find more info:

hope it's useful

Sign up to request clarification or add additional context in comments.

2 Comments

Really helpful. What is the use of sequence in this case? even with parallel i see each record displaying one at a time.
Great! This is definition of the sequence keyword: The Sequence keyword runs commands in sequence within a Parallel script block. The Sequence script block runs in parallel with other commands, but the commands within the sequence script block run sequentially and in the specified order. Have a look at this for some examples :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.