Common Variables for Multi-Thread Processing in Workflow in Powershell

Asked 2 years ago, Updated 2 years ago, 99 views

You want to run multiple ps1 scripts in parallel with workflow and ForEach-parallel.Each ps1 script returns $True or $Flase as a return value.I'm trying to count $Flase, but the scope is unable to use the variables in the script.

I would like to count the errors as below, but I cannot.Do you have any good ideas?

workflow func1{
    $Errors = 0
    ForEach-parallel ($i in 1..30) {
        US>InlineScript { 
            $ret=c:\scripts\test2.ps1
            if(!$ret)
            {
                $Errors+=1
            }
            write-host$Errors
        }
    }


}

func1

If you look at the page below, it says "there is no $global scope".
https://devblogs.microsoft.com/scripting/powershell-workflows-restrictions/

powershell

2022-09-30 21:39

1 Answers

Here Variables in an InlineScript Activity explains how to use it.

In order to access the workflow variable from the InlineScript, you must add $Using: only once.

Also, in order to reflect the changed value in InlineScript in the workflow variable, it seems to be notified and substituted as a return value in InlineScript.

Incidentally, to access the workflow variable from the Parallel sequence, you may need to add $Workflow:, so you may need to combine both or something else.
Variables in Parallel and Sequence Statements

Recommendation for Windows Workflow Foundation 4.0 (WF) on PowerShell in the Variable Specification in Workflow Syntax section, but it doesn't seem to explain Donpisha.

Rather than counting up or displaying in InlineScript, it would be better to set the return value of each ps1 to the return value of InlineScript and process it in the ForEach loop.

Also, according to the Japanese article above, Write-Host cannot be used in workflow, but I wonder if it can be used to increase the number of versions.It says to use Write-Output, Write-Warning, and Write-Verbose.

Other references with slightly different properties Q&A
Foreach-parallel object

I tried to replace the script with Get-Random and finally output the variable only the results.
Windows 10, PowerShell 5.1 console screen worked.

workflow func1{
    $Errors = 0
    ForEach-parallel ($i in 1..30) {
        $ret = InlineScript {Get-Random-Minimum1-Maximum20}
        $retnum = [int]$ret
        if ($retnum-gt10)
        {
            $Workflow: Errors + = 1
        }
    }
    InlineScript {Write-Host$Using: Errors}
}


2022-09-30 21:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.