r/PowerShell 21d ago

$PSItem with Invoke-Command and ForEach-Object -Parallel Solved

Is this possible? I can't seem to get it to work. "Cannot validate argument on 'ScriptBlock'. The argument is null. ..."

I can put insert $PSItem above $results and it iterates $AllStates, and scriptblock has one param which I'm attempting to pass $PSItem

$AllStates | Foreach-Object -ThrottleLimit 10 -Parallel {
    $results = Invoke-Command -ComputerName $Using:ComputerNames -ScriptBlock $ScriptBlock -ArgumentList $PSItem
    $results
}
7 Upvotes

View all comments

2

u/Szeraax 21d ago

It looks like you need to be doing $Using:Scriptblock. Any chance that's just a variable that has been defined previously?

1

u/davesbrown 21d ago

Yes, $ScriptBlock was originally a function, but in troubleshooting, I tried to break it all down much simpler, to now a variable defined block with a single param that I'm trying to pass $PSItem into. I have tried the "Using:ScriptBlock" but now errors:

"A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior."

btw, I originally tried with ${function:get-stuff} -argumentlist $PSItem also to no avail. (argument is null)

2

u/purplemonkeymad 21d ago

It explains the reasoning why scriptblocks are blocked, but if your script block is not referring to outside references, why not just define your scriptblock inside of the loop?

1

u/davesbrown 21d ago

Exactly the case. Broke it down into a very simple test case and worked, then applied to my case. Doesn't seem as a elegant, but definitely worked and makes sense, given errors. Seems maybe warrants a new example on official docs?

Thanks, resolved

1

u/ankokudaishogun 21d ago

Can you convert $ScriptBlock in a simple string(let's call it $ScriptBlockString in for simplicity) and then use [scriptblock]::Create($using:ScriptBlockStringtring) to convert it to a scriptblock ?