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
Avatar

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.

2 thoughts on “How to Create a Function in PowerShell

  • Avatar
    August 22, 2018 at 5:49 am
    Permalink

    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

    Reply
  • Avatar
    December 4, 2019 at 5:58 am
    Permalink

    Thanks for explaining it in a very systematic way.Really apprecaite it.

    Reply

Leave a Reply

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

*