Powershell Functions




A function is a block of code that will be executed when "someone" calls it:
Function Syntax
A function is written as a code block (inside curly { } braces), preceded by the function keyword:
Calling a Function with Arguments
When you call a function, you can pass along some values to it, these values are called arguments or parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, in specified order, if want to change the order of arguments or parameters passed then have to specify the argument name with "-".
myFunc { Param ([int] $var1, [int] $var) .. play with the variable function parameters. }
The variables and the arguments must not be in the expected order. You can specify the argument name with "-". Please see the example below,

Functions With a Return Value Sometimes you want your function to return a value back to where the call was made. This is possible by using the return statement. When using the return statement, the function will stop executing, and return the specified value.

Example 1: Addtion of two numbers

Example


function add
{
Param ([int] $a, [int] $b)

return $a + $b
}

add -a 5 -b 4

Copy and Try it


Output : 9
Powershell intelligent enough to identify the parameters in order or you specify the parameters or combination of these.
In below example one of the argument is specified and another one is not still powershell identifies then parameters.

Example 2 :

Example

function add
{
Param ([int] $a, [int] $b)

return $a - $b
}

add -b 5 4

Copy and Try it


Output: -1
Example 3: With validation

Example

Function Create-MyFoldler
{
	Param([string]$rootPath= $(throw"$rootPath required."), [string]$subFolder)

	if ([System.String]::IsNullOrEmpty($subFolder))
	{
		$folderToCreate=$rootPath
        write-host "Output 1:-" + $folderToCreate
	}
	else
	{
		$folderToCreate=Join-Path$rootPath$subFolder
        write-host "Output 2:-" + $folderToCreate
	}
	
    if (![IO.Directory]::Exists($folderToCreate)) 
	{
		New-Item $folderToCreate -ItemType directory
        write-host "Output 3:-" + $folderToCreate
	}
}


Create-MyFoldler -rootPath "c:\test"

Copy and Try it