powershell - Foreach - 并行对象

标签 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'}

最佳答案

好的,你去吧,尝试和测试:

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 并在整个工作流程中重复使用以访问范围。

关于powershell - Foreach - 并行对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37881875/

相关文章:

c# - 在 Parallel.ForEach 中嵌套 await

powershell - 从PowerShell中的后台作业中调用的函数获取返回值

internet-explorer - PowerShell - Internet Explorer : 0x80010108 (RPC_E_DISCONNECTED)

visual-studio - 在 Visual Studio 中引用 system.management.automation.dll

github - 为通过 GitHub 操作执行的单元测试运行本地主机服务器

git - 将 git 分支用于项目的变体

powershell - 在文档中插入对象

c# - 需要工作流程编辑软件 - 推荐

c# - Parallel.ForEach 中的迭代器在多个线程上运行

C# 并行 foreach - System.AggregateException : One or more errors occurred. ---> System.IndexOutOfRangeException