powershellnull

Why am I getting "InvalidOperation: You cannot call a method on a null-valued expression." only when using `-Parallel`?


I am using Powershell version 7.4.6

And I don't understand this behaviour.

I have a regular expression

$r = New-Object System.Text.RegularExpressions.Regex "a+"

and when I run it

( 'a', 'aa', 'aaa', 'b' ) | ForEach-Object { $r.isMatch( $_ ) }

I get the expected:

True
True
True
False 

but if I try to run it with -Parallel like:

    ( 'a', 'aa', 'aaa', 'b' ) | ForEach-Object -Parallel { $r.isMatch( $_ ) }

I surprisingly get:

InvalidOperation: You cannot call a method on a null-valued expression.
InvalidOperation: You cannot call a method on a null-valued expression.
InvalidOperation: You cannot call a method on a null-valued expression.
InvalidOperation: You cannot call a method on a null-valued expression.

Why


Solution

  • You will need to use the using: scope modifier to pass-in the Regex instance to the parallel scope, it's also required to enclose the expression in parentheses due to a parsing error:

    $r = [regex]::new("a+")
    'a', 'aa', 'aaa', 'b' | ForEach-Object -Parallel { ($using:r).IsMatch($_) }