Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2008-12-13
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
Categories: PowerShell
Tags: Functions
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply