Anitha
Anitha

Reputation: 149

PowerShell functions

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?

Upvotes: 2

Views: 2552

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

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.

Upvotes: 6

Related Questions