Saturday, February 3, 2018

Mysterious parameter binding errors? Wrap casts in parentheses

Today I dealt with some mysterious PowerShell errors associated with Add-Member. This code...

$x = New-Object psobject
$x | Add-Member NoteProperty 'SomeProp' [int]($something.someString)

...produced this error...
Add-Member : The SecondValue parameter is not necessary for a member of type "NoteProperty", and should not be
specified. Do not specify the SecondValue parameter when you add members of this type.
At line:1 char:6
+ $x | Add-Member NoteProperty 'SomeProp' [int]($something.someString)
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Add-Member], InvalidOperationException
    + FullyQualifiedErrorId : Value2ShouldNotBeSpecified,Microsoft.PowerShell.Commands.AddMemberCommand

I had added the parentheses around the string value because otherwise SomeProp became some text including what I meant to be the cast. Adding explicit parameter names to the Add-Member call had no effect. The solution is to wrap the entire cast in parentheses:

$x | Add-Member NoteProperty 'SomeProp' ([int]($something.someString))

No comments:

Post a Comment