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 the syntax of a simple function
function hello-world
{
write-host "hello world"
} You can also pass parameters in a function using the 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 a function by using the return keyword. The function when called returns a value
function Get-TimesResult {
Param ([int]$a,[int]$b)
$c = $a * $b
return $c
} You call this function and store its returned value in some variable
$r= Get-TimesResult -a 5 -b 5
Want to see more PowerShell command examples? Check out our guide on how to create a directory using PowerShell.