Powershell pass switch to scriptmethod - by SteveDeS

Status : 


Sign in
to vote
ID 791130 Comments
Status Active Workarounds
Type Bug Repros 0
Opened 6/27/2013 12:01:15 AM
Access Restriction Public


Is there a correct syntax for passing a switch to a scriptmethod like you can to a function

you can pass a switch to a function:

function func ($parm1,$parm2='defaultvalue',[switch]$switch1) {write-host $switch1}

func -switch1


How do you pass a switch to a scriptmethod ?

$obj = New-Object Object

Add-Member -in $obj ScriptMethod 'method' { param($parm1,$parm2,[switch]$switch1) write-host $switch1 }

$obj.method(-switch1) # doesn't work
Sign in to post a comment.
Posted by SteveDeS on 7/5/2013 at 10:04 AM
powershell.com got the most discussion: http://powershell.com/cs/forums/p/13485/25017.aspx#25017
I'm concluding that ScriptMethods just don't receive/handle parms the same as functions. Whether this is an architectural necessity or just an inconsistency, I'll leave up to the architects.
Posted by SteveDeS on 6/29/2013 at 3:03 PM
Thanks, I've added the post to those forums.
This could possibly be an enhancement request if it is not possible to pass switches to scriptmethods.
My reasoning is:

The advantage of the way functions handle things is that you don't have to specify every positional parm or switch if they are not needed for the particular call or their default value is adequate (like how cmdlets work). If you add a parm3 later, you don't have to revisit every call and add that parm unless it is needed.

As far as I can tell, with scriptmethods, you'd need to set values for and specify every parm and switch positionally. If you add a parm3 later, you'd have to go to every function call and adjust it.

You might ask, 'then why don't you just use functions'. I would like to use the object model where you keep the data attached to the object (I use note properties) and then the methods to manipulate that data.
Posted by Bob McCoy on 6/29/2013 at 11:15 AM
Also Forums at PowerShell.org
Posted by Bob McCoy on 6/29/2013 at 11:09 AM
Connect is for providing feedback to the product group (bugs, suggestions). If you need help scripting you might want to try one of these resources:

The Official Scripting Guys Scripting Forum

Forums at PowerShell.com