I’m trying to add an object of a class as a NoteProperty to another class inside a ForEach-Object -Parallel block in PowerShell 7. However, when I try to call a method on that added NoteProperty, I get an "Object reference not set to an instance of an object"
error. Here’s a simplified version of my code:
class test {}
$test = [test]::New()
1..2 | ForEach-Object -Parallel {
class test2 {
testmethod () {
Write-Host "test method called"
}
}
Add-Member -InputObject $using:test -MemberType NoteProperty -Name "property$_" -Value ([test2]::New())
}
$test.property1.testmethod()
If I do a Get-Member on $test.property1
I get the method testmethod
in the output.
I understand that the issue might be related to how objects and properties are scoped within the parallel block. How can I correctly add the NoteProperty and ensure that the method call works outside the parallel block?
enter image description here
enter image description here
It works with simple ForEach-Object without -Parallel.
SmoothJarManiac is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.