Powershell-Function

What is Function?
A function is a block of code that has a name and it has a property that it is reusable. Like in other programming language we can create function in powershell as well, it is basically groups a number of program statements into a unit and function is given name to it.
This unit can be invoked from other parts of a program.


Function Syntax:

Example


function FunctionName (parameters)
    {
    #script block
    }

Copy and Try it

Example


Function MyFunctionGetTime 
    {
        Get-Date
    }

Copy and Try it


To get execute function just give the function name. PS c:\>MyFunctionGetTime

By use of fuction we can do the script organization. We can reuse the code.
Use of function give you ability to call script blocks multiple times.

Example


function Addtion ([int] $x, [int] $y) {
$z = $x+ $y
#"Function is running"
return $z
}
#someFunction (5, 4) --Wrong 
$b = someFunction 5 4   --right 
$b # sum of tow valies
$z # Default value zero here as it is out of scope 


Copy and Try it


By default, all variables created in functions are local, they only exist within the function (they are still visible if you call a second function from within this one.) e.g. "$z" shows ZERO as it local for function block.
Supported data types in Powershell

Try-Catch-Finally
You can intercept any error in try, catch and finally statements.

PowerShell supports try/catch/finally, that should feel familiar to all java, .Net developers.

PowerShell Version 1 introduced the trap statement that still works; I prefer try/catch/finally.

If you are familar with any other programming language, like other programming languages commands you should execute should be placed in try block.
$error variable should be written in catch block.
Finally as name suggest, you should do the clean up or release the occupied resourses if any.

Example


    try {
        Remove-Item "C:\doentexist\file.txt" -ErrorAction Stop
    }
    catch [System.Management.Automation.ItemNotFoundException] {
        Write-Host "item not found" -ForegroundColor red
    }
    catch {
        Write-Host "undefined errors" -ForegroundColor orange
        Write-Host $error[0] -ForegroundColor orange
    }
    finally {
        "Finally block"
    }

Copy and Try it

Continue

Function Exit

Function Break

Do While Function Loop

Write function in differnet file and include files /call functions from another file
1. Create psFunctions.ps1 and write some 'XYZ-Function' accepts 2 input parameter (param1, param2) which will return something .
2. Include file calling file in master file.
e.g.

Example

    #Include functions file
    . "$scriptPath/psFunctions.ps1"
        
    

Copy and Try it


3. Now try to attempt to directly call function

Example

    $sample1 = XYZ-Function param1 param2
    
    

Copy and Try it


4. This way you include and call function from master file.