问题
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