Answer the question
In order to leave comments, you need to log in
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
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question