Defining and calling functions

You can define your own functions in a PowerShell script file (PS1-file) or directly from the PowerShell console. To do this, use the keyword function, followed by the definition encapsulated in curly brackets. This code creates a function that returns a string containing the phrase “String returned from a function!”:

function myFunction { “String returned from a function!” }

To call this function, simply type myFunction and press Enter. A tip for avoiding typing long lines, you do line breaks by pressing Shift+Enter after the first line. PowerShell then enters a line editing mode. To send the text to PowerShell end exit the line editor, just pres Enter twice. PowerShell might look like this after entering and leaving the line editor:

PS H:\> function myFunction
>> {
>> “String returned from a function!”
>> }
>>

If the function you’re designing requires parameters, you can declare them in a comma separated list directly after the function name. This line defines the sum function that takes two integer parameters and returns the sum of the given values.

function sum([int]$p1, [int]$p2) { $p1+$p2 }

To call a function with parameters, enter the function name followed by the parameter values (constants or variables) separated by nothing but a whitespace.

sum 10 20

To nest the function, encapsulate it in parenthesis. This call returns the value 46:

sum (sum 10 15) 21

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll:

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Comments

Important information: If you have not commented before, your comment will be reviewed before it is published. This means that you will not see it immediately, but I have received it. This is not because I want to filter comments, but because I want to prevent spam and advertising.

Leave a Reply

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