powershellpowershell-workflow

Trouble Understanding Powershell Workflow ForEach


I'm trying to get my feet wet with Powershell Workflows and some work I need to do in parallel.

I didn't get very far before hitting my first roadblock, but I don't understand what I'm doing wrong here:

$operations = ,("Item0", "Item1")

ForEach ($operation in $operations) {
    Write-Output "Item0: $($operation.Item(0)) Item1: $($operation.Item(1))"
}

workflow operationsWorkflow{
    Write-Output "Running Workflow"
    $operations = ,("Item0", "Item1")
    ForEach -Parallel ($operation in  $operations) {
        #Fails: Method invocation failed because [System.String] does not contain a method named 'Item'.
        #Write-Output "Item0: $($operation.Item(0)) Item1: $($operation.Item(1))"

        Write-Output "Item $operation"
    }
}

operationsWorkflow

Solution

  • Problem solved, thanks to this excellent article on powershell arrays

    Now, since it’s already an array, casting it again doesn’t result in a second level of nesting:

    PS (66) > $a = [array] [array] 1

    PS (67) > $a[0]

    1

    However using 2 commas does nest the array since it is the array construction operation:

    PS (68) > $a = ,,1

    PS (69) > $a[0][0]

    1

    Given that, this works fine:

    workflow operationsWorkflow{
        Write-Output "Running Workflow"
        $operations = ,,("Item0", "Item1")
        ForEach -Parallel ($operation in  $operations) {
                Write-Output "Item0: $($operation.Item(0)) Item1: $($operation.Item(1))"
        }
    }
    
    operationsWorkflow
    

    However, if the second comma is added outside the workflow, then errors occur there. So this is a workflow or parallel specific issue and workaround.