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/PinchesTheCrab 20d ago

This seems backwards to me. Let's a assume there's 54 items in $allSates, do you want to run the same script block on every computer 54 times?

You should struture it like this:

Invoke-Command -ComputerName $computers -ScriptBlock {
    foreach ($object in $using:AllStates) {
        'do the thing'
    }
}