2

What I understood is "Functions in PowerShell scripting are named code block which enables an easy way to organize the script commands."

& Define using:

Function [Scope Type:]<Function name>

For Example:

Function Test
{
    Write-Host "Test method"
} 
Test

Functions with parameters

Example:

Function Test( $msg)
{
    Param ([string] $msg)
    Write-Host "$msg"
} 
Test "Test method"

Output:

Test method

Parameter types:

  1. Named params: Param ([int] $first,[int] $second)

  2. Positional Params: $args[0], $args[1]

  3. Switch params: Param([Switch] $one,[Switch] $two)

  4. Dynamic params: Set-Item -path alias:OpenNotepad -value c:\windows\notepad.exe

How do these "switch parameters" work in PowerShell scripting?

3

1 Answer 1

6

It's like a Boolean, but you don't have to (but can) pass $true or $false to it. Example:

function Test-SwitchParam
{
    Param(
        [Switch] $one,
        [Switch] $two
    )

    if ($one)
    {
        Write-Host "Switch one is set"
    }

    if ($two)
    {
        Write-Host "Switch two is set"
    }
}

Now you can call the function like:

Test-SwitchParam -one

The switch $one will be $true, because it is set, and $two will be false.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.