[switch] $NoInheritance - Powershell Code

Kelly Garcia
Kelly Garcia used Ask the Experts™
on
Hi All,

I am trying to understand this line of code, what exactly is the [switch] $NoInheritance ? how does it work?

function DoPermissions
{
    param( $permissionGroup, $folder, $level, [switch] $NoInheritance)
}

Open in new window


Thank you in advance
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
A switch is an optional parameter without (explicit) value (in fact it is a boolean). If left out when calling the function, it is $false, if you call with -NoInheritance it is $true.
You can call it with an explicit value, which you might want to do if the default value differs from $false, by e.g. using -NoInheritance:$false.
Kelly GarciaSenior Systems Administrator

Author

Commented:
ok I kind of get it, if do dopermissions --NoInheritance it will:

switch (noinheritance)
{
Pattern 1 {Statement block}
 Pattern 2 {Statement block}
 Pattern n {Statement block}
}

is this correct?
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
No. [switch] and switch are totally different kind of things. $NoInheritance just has the values $false or $true, depending on what has been provided or left out at calling the function.
Kelly GarciaSenior Systems Administrator

Author

Commented:
ok thank you, any examples to help me understand?
"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
function DoPermissions
{
    param( $permissionGroup, $folder, $level, [switch] $NoInheritance)
    if (!$NoInheritance)
    {
      <# code to add inheritance #>
    } else {
      <# code without inheritance #>
    }
}

# This are the same
DoPermissions -NoInheritance
DoPermissions -NoInheritance:$true

# This are the same, but reverse meaning to above
DoPermissions
DoPermissions -NoInheritance:$false

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial