Foreach -parallel object

痞子三分冷 提交于 2019-12-10 15:48:43

问题


Recently we started working on scripts that take a very long time to complete. So we dug into PowerShell workflows. After reading some documentation I understand the basics. However, I can't seem to find a way to create a [PSCustomObject] for each individual item within a foreach -parallel statement.

Some code to explain:

Workflow Test-Fruit {

    foreach -parallel ($I in (0..1)) {

        # Create a custom hashtable for this specific object
        $Result = [Ordered]@{
            Name  = $I
            Taste = 'Good'
            Price = 'Cheap'
        }

        Parallel {
            Sequence {
                # Add a custom entry to the hashtable
                $Result += @{'Color' = 'Green'}
            }

            Sequence {
                # Add a custom entry to the hashtable
                $Result += @{'Fruit' = 'Kiwi'}
            }
        }

        # Generate a PSCustomObject to work with later on
        [PSCustomObject]$Result
    }
}

Test-Fruit

The part where it goes wrong is in adding a value to the $Result hashtable from within the Sequence block. Even when trying the following, it still fails:

$WORKFLOW:Result += @{'Fruit' = 'Kiwi'}

回答1:


Okay here you go, tried and tested:

Workflow Test-Fruit {

    foreach -parallel ($I in (0..1)) {

        # Create a custom hashtable for this specific object
        $WORKFLOW:Result = [Ordered]@{
            Name  = $I
            Taste = 'Good'
            Price = 'Cheap'
        }

        Parallel {

            Sequence {
                # Add a custom entry to the hashtable
                $WORKFLOW:Result += @{'Color' = 'Green'}
            }

            Sequence {
                # Add a custom entry to the hashtable
                $WORKFLOW:Result += @{'Fruit' = 'Kiwi'}
            }


        }

        # Generate a PSCustomObject to work with later on
        [PSCustomObject]$WORKFLOW:Result
    }
}

Test-Fruit

You're supposed to define it as $WORKFLOW:var and repeat that use throughout the workflow to access the scope.




回答2:


You could assign $Result to the output of the Parallel block and add the other properties afterwards :

$Result = Parallel {
    Sequence {
        # Add a custom entry to the hashtable
        [Ordered]@{'Color' = 'Green'}                    
    }

    Sequence {
        # Add a custom entry to the hashtable
       [Ordered] @{'Fruit' = 'Kiwi'}
    }
}

# Generate a PSCustomObject to work with later on
$Result += [Ordered]@{
    Name  = $I
    Taste = 'Good'
    Price = 'Cheap'
}

# Generate a PSCustomObject to work with later on
[PSCustomObject]$Result


来源:https://stackoverflow.com/questions/37881875/foreach-parallel-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!