Share via


PowerShell: Writing Functions in PowerShell - Part 1

Summary

During my PowerShell session my team asked me to demo writing PowerShell functions. So this wiki article will cover all about functions

Help

As we all know it's best practice to use help before doing some scripting or snippets in PowerShell

help about_Functions

Best Practice

  • Try to avoid alias as much as possible.
  • Try avoiding pipelines.
  • Use Measure-Command and consume the best and which executes in less time.
  • Align the scripts - this helps others to read and understand before using help.
  • Document PowerShell functions - This helps to use HELP

Basic Function with static parameters to add two values

function Add-Values
{
    $value1 = 12
    $value2 = 12
    $value3 = 12 + 12
    $value3
}
Add-Values

Basic Function parameters to add two values - Passing Values to Parameters

function Add-Values ($value1 , $value2)
{
   $value3 = $value1 + $value2
   $value3
}
Add-Values -value1 12 -value2 22

Proper Basic Function

<#
.Synopsis
   PowerShell function demo to add values
.DESCRIPTION
   This is a PowerShell demo function. This function will add two values
.EXAMPLE
   Add-Value -value1 10 -value2 20
#>
function Add-Value
{
    [CmdletBinding()]
    Param
    (
        # Param1 - Enter any numbers below 2147483647
        [Parameter(Mandatory = $true)]
        [int]
        $value1,

        # Param2 - Enter any numbers below 2147483647
        [Parameter(Mandatory = $false)]
        [int]
        $value2
    )

    Begin
    {
    }
    Process
    {
        
        $result = $value1 + $value2
        $result
    }
    End
    {
    }
}

Add-Value -value1 2147483647 -value2 20

Screen Shot