Fun With Functions


posted by ps1
09-11-2008

Downloads: 566
File size: 790 B
Views: 2,989

Embed
Fun With Functions
  1. #A familiar function 
  2. function Add($number1, $number2
  3.     $result = $number1 + $number2 
  4.     return $result 
  5.  
  6. #Call the function Add. Notice we're not using Add(1,2) or Add 1, 2 
  7. Add 1 2 
  8.  
  9. #We don't even need return since the last value is automatically returned 
  10. function Subtract($number1, $number2
  11.     $number1 - $number2 
  12.  
  13. #Call it 
  14. Subtract 10 4 
  15.  
  16. #Optional parameters and initialization 
  17. function Multiply([int]$number1, [int]$number2=10) 
  18.     $number1 * $number2 
  19.  
  20. #Call it with just one value 
  21. Multiply 5 #returns 50 
  22.  
  23. #Call it with two strings 
  24. Multiply "test" "strings" #Error: Cannot convert value "test" to type "System.Int32" 
  25.  
  26. #Just for fun let's put a couple together. The parenthesis are required. 
  27. Multiply (Add 2 3) (Subtract 10 5) #returns 25 

This exercise illustrates some simple functions. Notice that when you call functions you don't use parenthesis or commas like a programmer might be inclined to do. Also notice that the we don't even need to use the keyword return since the last value of the function is automatically returned.

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.