PowerShell: How to use Switch Parameter?

PowerShell: How to use Switch Parameter?


What is Switch Parameter?

Help about_Functions_Advanced_Parameters

How to Use Switch Parameter?

Param(

    [Parameter(Mandatory=$false)]

    [Switch]$ColorText

    )

 

How to consume switch parameter?

Demo function if switch -colortext is included you get color text output if not plain text with default host color.

Function Demo

 

{

    Param(

    [Parameter(Mandatory=$false)]

    [Switch]$ColorText

    )

 

if($ColorText -eq $false)

    {

        Write-Host "Plain Text"

    }

elseif($ColorText -eq $true)

    {

        Write-Host "Color Text" -ForegroundColor Green

    }

 

}


Sort by: Published Date | Most Recent | Most Useful
Comments
  • thanks for sharing.

  • I just watched a YouTube  video (www.youtube.com/watch) that showed a better way to do this. Get rid of the elseif lines and change the if statement to

    if ($ColorText.IsPresent)

    {Write-Host "Color Text" -ForeGroundColor Green

    }

    This way, all you have to do to call this portion in the command is to use the -ColorText parameter. If you write your module using the way described in this article, you would have to use -ColorText $true which is obviously more clunky.

  • Function Demo

    {

       Param(

       [Parameter(Mandatory=$false)]

       [Switch]$ColorText = $false

       )

        if($ColorText){

           Write-Host "Color Text" -ForegroundColor Green

        }else{

          Write-Host "Plain Text"

        }

    }#End Function

Page 1 of 1 (3 items)