1

I'm working on a PowerShell script that needs to use ForEach-Object -Parallel to run several iterations of a process simultaneously. Here's my code (with names changed to protect the innocent). Right now, I have essentially a copy of the function in the loop by converting it to a string (I found that in another answer here on SE).

If I try to use a constant in one of these functions, it comes up empty, even though every constant I have is declared in the highest scope. Also, my "ProcessItem" function doesn't recognize any other declared functions and errors out if I try to call one of them.

I'm using Powershell 7.5, and I don't have any errors in the constants or functions themselves (which I have verified by running each one in its own environment). If I comment out the calls to other functions and replace the constants with hard-coded values, the program runs all the way through without dying.

# Number of seconds between the process
Set-Variable -Name WAIT_TIME -Option Constant -Value 5

$ProcessItemString = ${function:ProcessItem}.ToString()

0..($allItems.Count - 1) | ForEach-Object -Parallel {
    ${function:LocalProcessItem} = $using:ProcessItemString

    $a, $b = LocalProcessItem -itemID ($using:allItems)[$_].item_id -category ($using:allItems)[$_].category -requests $using:requests

    echo $a
    echo $b
} -Throttle 20

So here's my question: Is there a way to make those constants and functions accessible inside of these other threads?

I'm more concerned about the function calls than the constants, but if there's a way to make them invokable without just making them a subfunction, that would be preferrable.

EDIT: I don't know if this affects the answer at all, but this process will be going through 2000 items, and I will be setting the throttle value higher before actually running the whole thing.
I've figured out the constants, but not the functions yet.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.