2
votes

I've tried two ways to instantiate a class in Powershell v3:

$regex = New-Object -Type System.Text.RegularExpressions.Regex -ArgumentList '\/\/.*' | Get-Member
$regex::Replace("//hey", "")

And:

$netregex = [regex]::new('\/\/.*') | Get-Member
$nosingleline = $netregex::Replace("//hey", '')

The first way yields this:

Unable to cast object of type 'System.Object[]' to type 'System.Type'.

At line:2 char:1

  • $regex::Replace("//hey", "")
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : OperationStopped: (:) [], InvalidCastException
    • FullyQualifiedErrorId : System.InvalidCastException

The second way yields this:

Method invocation failed because [System.Text.RegularExpressions.Regex] doesn't contain a method named 'new'. At line:4 char:1

  • $netregex = [regex]::new('//.*') | Get-Member
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : MethodNotFound
1

1 Answers

3
votes

Remove | Get-Member from both commands. It is changing the ultimate object type being output on those lines.

Also use . to access the method:

$netregex = [regex]::new('\/\/.*')
$nosingleline = $netregex.Replace("//hey", '')

$regex = New-Object -Type System.Text.RegularExpressions.Regex -ArgumentList '\/\/.*'
$regex.Replace("//hey", "")