Functions and Subs


VBScript and PowerShell declare functions similarly. Here's a function in VBScript that returns True if the input parameter is more than 5, otherwise it returns False:

 Function IsMoreThan5(intValue)   If intValue > 5 Then     IsMoreThan5 = True   Else     IsMoreThan5 = False   End if End Function 

Notice that VBScript returns a value by setting the function name equal to the return value. PowerShell works similarly:

 Function IsMoreThan5($Value) {   If ($Value -gt 5) {     Return $true   } Else {     Return $false   } } 

Notice that the Return keyword is used to return the function's value. In fact, any output of the function will be appended to the return value. The following is functionally identical:

 Function IsMoreThan5($Value) {   If ($Value -gt 5) {     $true   } Else {     $false   } } 

This example shows that outputting $true or $false into the pipeline makes those values the function's return value. Refer to Chapter 10 to review the discussion of how functions have significantly expanded capabilities in PowerShell.

PowerShell does not provide a separate Sub construct as VBScript does. However, a Function that returns no value is essentially the same as a Sub.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net