If you have worked with other programming languages, you have may used functions for code reusability. You can also create functions in PowerShell.

PowerShell function example

Below is syntax of simple function

function hello-world 

{ 

write-host "hello world" 

}
You can also pass parameters in a function using param keyword
function Get-TimesResult {

Param ([int]$a,[int]$b)

$c = $a * $b

Write-Output $c

}
You can call a function using its name like
hello-world
and if a function is taking some parameters type
Get-TimesResult -a 5 -b 10
You can also return a value from function by using return keyword. The function when called return a value
function Get-TimesResult {

Param ([int]$a,[int]$b)

$c = $a * $b

return $c

}

You call this function and store it's returned value in some variable 

$r= Get-TimesResult -a 5 -b 5


 

How to Create a Function in PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *

*