in powershell, splatting Update-TypeData giving error ScriptMethod not recognized

Viewed 41

I'm wondering why the following code gives me the error: "ScriptMethod" is not recognized as the name of a cmdlet, function, script file, or operable program.

I look in the dotnet documentation for this field and it says:

-MemberType
Specifies the type of the member to add or change.

Use this parameter with the TypeName, MemberType, Value and SecondValue parameters to add or change a property or method of a type. The acceptable values for this parameter are:

AliasProperty
CodeMethod
CodeProperty
Noteproperty
ScriptMethod
ScriptProperty
For information about these values, see PSMemberTypes Enumeration.

Here's the code with the error:

$proto = @{
    Force = $true
    TypeName = "System.String"
    MemberName = "RegexCount"
    MemberType = ScriptMethod
    Value = {
        param([regex]$Regex)
        $Regex.Matches($this).Count
    }
}

Update-TypeData @proto

1 Answers

tl;dr

Replace MemberType = ScriptMethod with:

  • either: MemberType = 'ScriptMethod'
  • or: MemberType = [System.Management.Automation.PSMemberTypes]::ScriptMethod

According to PowerShell's parsing rules, ScriptMethod in your hash-table entry,
MemberType = ScriptMethod, is parsed in argument (command) mode, i.e. the unquoted ScriptMethod token is interpreted as the name of a command - and since no such command (typically) exists, you got an error.

You need expression mode, in which string literals such as ScriptMethod must be quoted in order to be recognized as such.

By contrast, the hashtable key names, e.g. MemberType, only require quoting if they contain metacharacters such as spaces.

The Update-TypeData target parameter, -MemberType is ultimately of enumeration type [System.Management.Automation.PSMemberTypes], so you may pass such an enumeration value explicitly, as shown above, but that is verbose and generally not necessary, because PowerShell automatically converts strings to and from enumeration types as needed.

Related