PowerShell function is similar to other programming language functions, mainly related to input parameters, processing, output parameters, return value, how to invoke the content, described below.
1, PowerShell function definition
The definition function uses the function keyword, uses a custom identifier as the name of the functions, and encloses the function body with a pair of curly braces. As follows:
Copy Code code as follows:
Function < function name >{
< function body >;
}
Example:
Copy Code code as follows:
function test-fun{
$args 0 = $args [0]
$args 1 = $args [1]
Write-host "p1= $args [0], p2= $args [1]"
Write-host "p1= $args 0, p2= $args 1"
}
In doing this example, Hongo encountered a very sad push scene. Two output modes that feel exactly the same, the result is quite different. Hongo can only say, double quotes in the $args variable, incredibly regardless of the back of the brackets and subscript, really tmd too weird, careful use! The truth is as follows:
Copy Code code as follows:
PS > Function test-fun{
>> $args 0 = $args [0]
>> $args 1 = $args [1]
>> $msg = "p1= $args [0], p2= $args [1]"
>> write-host "p1= $args [0], p2= $args [1]"
>> Write-host $msg
>> write-host "p1= $args 0, p2= $args 1"
>>}
>>
PS > Test-fun 111 222
p1=111 222[0], p2=111 222[1]
p1=111 222[0], p2=111 222[1]
p1=111, p2=222
2, PowerShell function input parameters
In the function body, use the Param () method to define the input parameters for the function, as follows:
Copy Code code as follows:
Function < function name >{
Param ($p 1, $p 2,...);
< function body >;
}
For more details on the PowerShell function input parameters, such as "Positional parameters", "Name Parameters", "Parameter Properties", and so on, please go to the "PowerShell tutorial PowerShell function input parameters."
3, PowerShell function return value
PowerShell will package the output from all function bodies into a System.Array object as the return value. Although PowerShell also supports the return statement, the sentence described earlier in Hongo is still valid. So, this return is a device.
4. PowerShell function call
The call to function is very simple, similar to the way VB calls a function. As follows:
Copy Code code as follows:
< function name > [[-parameter number 1] parameter value 1[, [-parameter name 2] parameter value 2], ...]
Example:
Test-fun "parameter Value"
Test-fun "parameter value 1", "parameter value 2", "Parameter value 3"
Test-fun-p1 "parameter value 1"-p2 "parameter value 2"