1

foreach -parallel在工作流中使用循环时,我们如何将项目添加到数组列表powershell

workflow foreachpsptest { 
  param([string[]]$list)
  $newList = [System.Collections.ArrayList]@()
  foreach –parallel ($item in $list){
    $num = Get-Random 
    InlineScript {
      ($USING:newList).add("$num---$item")
    }
  }
  Write-Output -InputObject "randomly created new List: $newList"
} 
$list = @("asd","zxc","qwe","cnsn")
foreachpsptest -list $list
4

2 回答 2

1

这里的问题是你使用,呃$using:错误的方式。

您的工作流程基本上是它自己的沙箱。您可以使用 $using 来实例化其中具有相同值的变量,但不能使用它来操作它之外的相同变量。

但是,您可以让工作流发出一个对象,然后使用$newlistArraylist 变量的 .Add() 方法捕获该对象。

像这样调整代码,它应该可以工作:

#Moved the Arraylist declaration outside
$newList = [System.Collections.ArrayList]@()

workflow foreachpsptest { 
param([string[]]$list)
foreach –parallel ($item in $list){
      $num = Get-Random 
      InlineScript {
      #use the using: context to pass along values, then emit the current object
      "$using:num---$using:item"
      }
}
} 

$list = @("asd","zxc","qwe","cnsn")
#kick off the workflow and capture results in our arraylist
$newList.add((foreachpsptest -list $list))

然后,在代码运行之后,我们可以像这样获取值。

$newList
58665978---qwe
173370163---zxc
1332423298---cnsn
533382950---asd
于 2016-01-28T14:53:56.663 回答
0

我不认为你能做到这一点。 这篇关于 Powershell 工作流限制的文章将“对象上的方法调用”称为不受支持的活动,因此.add()您的 arraylist 上的方法将不起作用。

于 2016-01-28T14:44:49.130 回答