Foreach - 并行对象 [英] Foreach -parallel object
问题描述
最近我们开始编写需要很长时间才能完成的脚本.因此,我们深入研究了 PowerShell 工作流程.阅读一些文档后,我了解了基础知识.但是,我似乎找不到为 foreach -parallel
语句中的每个单独项目创建 [PSCustomObject]
的方法.
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.
一些代码解释:
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
出错的部分是从 Sequence
块中向 $Result
哈希表添加值.即使尝试以下操作,它仍然失败:
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'}
推荐答案
好的,已经试过了:
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 并在整个工作流程中重复使用以访问范围.
You're supposed to define it as $WORKFLOW:var and repeat that use throughout the workflow to access the scope.
这篇关于Foreach - 并行对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!