Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Powershell pass switch to scriptmethod

$
0
0

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

True

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

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.

 


Viewing all articles
Browse latest Browse all 6937

Trending Articles