Changes

Jump to: navigation, search

Windows PowerShell 1.0 Functions

2,333 bytes added, 20:03, 4 December 2008
Specifying Function Parameter Types
At line:1 char:9
+ multiply <<<< 4 "five"
</pre>
 
== Using Functions in a Pipeline ==
 
As discussed in previous chapters, Windows PowerShell allows cmdlets to be executed in a sequence, with the results from one cmdlet used as input to the next cmdlet in the pipeline chain. Pipelines are created by separating the cmdlets by the pipe character (|). In order to include a function in a pipeline it is necessary for that function to process the $input variable. This variable contains the results from the previous cmdlet or function in the pipeline. In the following example, a function named ''filelengths'' is designed to take the output from the ''dir'' cmdlet'', iterate through the ''$input'' variable and display the name and length of each file:
 
<pre>
function filelengths
{
foreach ($file in $input)
{
"Filename: " + $file + " Length: " + $file.length
}
}
</pre>
 
All that remains to test out this function is to pipe a ''dir'' command through to it:
 
<pre>
PS C:\Users\Administrator> dir *.txt | filelengths
Filename: C:\Users\Administrator\date.txt Length: 162
Filename: C:\Users\Administrator\error.txt Length: 334
Filename: C:\Users\Administrator\filename.txt Length: 16
Filename: C:\Users\Administrator\mydata.txt Length: 30
Filename: C:\Users\Administrator\mydatafile.txt Length: 8
Filename: C:\Users\Administrator\output.txt Length: 1120
</pre>
 
== Returning from Functions ==
 
By default a function will exit when execution reaches the end of the statements in the body. If a function needs to exit before all the statements have been executed (perhaps as the result of some conditional statement) this may be achieved using the ''return'' statement.
 
The ''return'' statement may be used to return silently as follows:
 
<pre>
function hello ($name)
{
if ($name -ne "Fred")
{
return
}
 
"Hello Fred!"
}
</pre>
 
Alternatively, the ''return'' statement can be used to return a value:
 
<pre>
function hello ($name)
{
if ($name -ne "Fred")
{
return "Sorry $name, I was looking for Fred!"
}
 
"Hello Fred!"
}
</pre>
 
When executed with the incorrect name as a parameter, the conditional statement will cause the function to output the ''Sorry'' message and exit before reaching the "Hello" statement.
 
<pre>
PS C:\Users\Administrator> hello john
Sorry john, I was looking for Fred!
</pre>

Navigation menu