Pass a System.Text.RegularExpressions.Regex as function parameter in Powershell 6

507 Views Asked by At

Hello Powershell Experts,

I want to write a Powershell function that takes a System.Text.RegularExpressions.Regex as a parameter. My function header goes like this:

function Foo {
    Param([System.Text.RegularExpressions.Regex] $myRegex)
    # function body
}

And I tried to call Foo like this:

$MY_REGEX = new-object System.Text.RegularExpressions.Regex('<regex_body>')
Foo($MY_REGEX)

I got an error that says Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Text.RegularExpressions.Regex".

I'm wondered why this is since I explicitly defined the regex with System.Text.RegularExpressions.Regex type. So I did .GetType() on my object and I got:

BaseType                   : System.Object
UnderlyingSystemType       : System.Text.RegularExpressions.Regex
FullName                   : System.Text.RegularExpressions.Regex

So now I'm confused why it's complaining about casting when the underlying type matches...

Can someone please point out what I'm doing wrong?

1

There are 1 best solutions below

2
On BEST ANSWER

From the command line the below works for me with a bit of the relevant output provided. Can you provide an full example.

function foo { param ( [System.Text.RegularExpressions.Regex] $myRegex ) ; process { Write-Information -MessageData $myRegex -InformationAction Continue ; $myRegEx.GetType() | fl * } }
foo a.
$r = New-Object System.Text.RegularExpressions.RegEx("a.")
foo -MyRegex $r

and emits

a.

FullName                   : System.Text.RegularExpressions.Regex

Try using the last syntax shown.