How to Create a Function in PowerShell

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
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


2 thoughts on “How to Create a Function in PowerShell”

  1. Hi,
    The functions are not working or I am missing something. It gives an error something like:
    Missing function body in function declaration.
    + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingFunctionBody


Leave a Comment