PowerShell : Functions

A function is a block of statements that have a name that you assign for easy re-use.

A function includes the following items:

  • Function keyword
  • Scope (optional)
  • Name
  • Parameters (optional)
  • PowerShell commands enclosed in braces ({})

Functions can return values that can be displayed, assigned to variables, or passed to other functions or cmdlets.

A simple function

function hello-world
write-host "hello world"

You can pass parameters in a function using param keyword

function Get-Result {
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-Result -a 5 -b 10

To define a default value for a parameter, type an equal sign and the value after the parameter name.

Function Scope

A function exists in the scope in which it was created. When a function is in the global scope, you can use the function in scripts, in functions, and at the command line.

function global:hello-world {
write-host "hello world"