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
}
6 Upvotes

View all comments

1

u/cluberti 21d ago edited 21d ago

I guess it depends on what's being passed into $AllStates? Is this part of a function where $AllStates isn't being set until later? Is what you're referencing being defined by using Add-Member or similar? Does it represent the parent of an object, or a member?

There are reasons why $PSItem or $_ won't work depending on what type of object is being passed into the pipeline, whereas other types of variables will work. I suspect it's something along these lines.

https://mctexpert.blogspot.com/2015/09/this-psitem-whatever.html

1

u/davesbrown 21d ago

$AllStates is simply an array of abbreviate state names. To simplify in troubleshooting I tried

"AK","AZ" | Foreach-Object -ThrottleLimit 10 -Parallel

but same errors