Foreach -parallel对象

时间:2016-06-17 12:42:59

标签: powershell workflow parallel.foreach

最近我们开始研究需要很长时间才能完成的脚本。因此我们深入研究了PowerShell工作流程。阅读完一些文档后,我了解了基础知识。但是,我似乎找不到为[PSCustomObject]语句中的每个项目创建foreach -parallel的方法。

有些代码需要解释:

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

出错的部分是在$Result块中向Sequence哈希表添加值。即使尝试以下操作,它仍然会失败:

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

2 个答案:

答案 0 :(得分:2)

好的,你去,试过并测试过:

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

您应该将其定义为$ WORKFLOW:var并重复使用整个工作流程来访问范围。

答案 1 :(得分:0)

您可以将$Result分配给Parallel块的输出,然后添加其他属性:

$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