S
S
Satisfied IT2021-07-02 11:23:28
PowerShell
Satisfied IT, 2021-07-02 11:23:28

How can a ForEach loop be converted to ForEach-​Object to parallelize execution?

We have a script that backs up each folder in turn from the list of folders along a given path, everything is backed up sequentially and it turns out for a very long time, while there are free resources. Therefore, there was a desire to make backup folders not sequentially, but in parallel. Google suggested that for this it is necessary to convert the ForEach loop to ForEach-Object and there it will already be possible to specify the parallel execution of commands, but here I have a dead end, I can’t figure out how to do it right. I have a loop like this, can anyone have experience with ForEach-Object and give a hint?

foreach ($item in $folderlist) {
    $bakname = TranslitToLAT $item.Name
    BackupFile -pathfolderbackup $item.FullName -backupName $bakname
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2021-07-02
specialist @borisdenis

Well, this is quite a basic syntax PS
Here you will see the difference in the syntax
https://stackoverflow.com/questions/29148462/diffe...
and I think you can already guess where to add the -Parallel parameter

M
Morrowind, 2021-07-02
@hekkaaa

Hey!
You need to use workflow and foreach -parallel as MaxKozlov
suggests. Note that you need to use Powershell version 5.1 in the field, it was cut out in later versions.
Here is an example of the code you need:
(the code simply copies files from one folder to another. I think you can integrate your backup using the example)

workflow Test-Workflow
{
    $Disk1 = Get-ChildItem C:\Temp\1

    # The disks are processed in parallel.
    ForEach -Parallel ($Disk in $Disk1)
    {
        $DiskFrom = "C:\Temp\1\$Disk"
        # The commands run sequentially on each disk.
        Copy-Item -Path $DiskFrom -Destination C:\Temp\2\
        
    }
    Write-Output "Files copied."
}

Test-Workflow

Hope it helped. Have a nice day!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question