Search code examples
arrayspowershellpowershell-workflow

Declaring arrays in powershell workflows


I need an array of size n in powershell workflow

workflow hai{
   $arr=@(1,2)
   $a=@(0)*$arr.Count #array needed
   for ($iterator=0;$iterator -lt $arr.Count;$iterator+=1){
        $a[$iterator]=$arr[$iterator]
   }
}

This shows error at the line

$a[$iterator]=$arr[$iterator]

We can use like this

workflow hai{
   $arr=@(1,2)
   $a=@()
   for ($iterator=0;$iterator -lt $arr.Count;$iterator+=1){
        $a+=$arr[$iterator]
   }
}

But my case is different where I have to access the array using index. Is there a way to do this in workflow


Solution

  • You get that error because workflow doesn't support assignment to an indexer. See this article for a number of limitations of workflow. Try using an inlinescript to get what you want e.g.:

    workflow hai{
       $arr = @(1,2)
       $a = inlinescript {
           $tmpArr = $using:arr
           $newArr = @(0)*$tmpArr.Count #array needed
           for ($iterator=0;$iterator -lt $newArr.Count;$iterator+=1){
               $newArr[$iterator] = $tmpArr[$iterator]
           }
           $newArr
       }
       $a
    }