PowerShell: Funciones | 10/14 | UPV
How to Use Functions in Windows PowerShell
Introduction to Functions
- Augustina Espinoza introduces the presentation, focusing on utilizing functions in Windows PowerShell.
- The session will cover function declaration, usage, return values, alternative parameter declarations, and default values for parameters.
Declaring and Using Functions
- To declare a function, use the
functionkeyword followed by the name, a list of parameters, and statements. It's advisable to restrict argument types for better error detection.
- Restricting argument types aids in type conversion and enhances error detection during function execution.
- Call a function using its name followed by arguments; these can be positional or named without needing to follow the order of declaration.
Function Execution Example
- An example shows calling a function with dates: January 1st and January 3rd of 2015 as arguments.
- The function executes and displays all dates between the specified start and end dates inclusively.
- A second call demonstrates retrieving dates between February 10th and February 11th of 2015.
Return Values from Functions
- Discusses how functions return values implicitly when reaching the end of their statement block without an explicit return statement.
- Any generated expressions that are not assigned to variables are returned automatically by the function upon completion.
- In an example script generating dates between February 10th and February 11th, results show how variable assignment works with returned values.
Alternative Parameter Declaration
- Introduces an alternative method for declaring parameters within a specific block indicated by the
paramkeyword instead of after the function name.
- This approach is beneficial if future functionality aligns with commandlets regarding execution behavior and documentation.
Handling Missing Arguments
- Explains what happens when no argument is provided for certain parameters; they may default to null. It’s crucial to account for this possibility in implementation.
- Demonstrates setting missing date arguments equal to initial ones resulting in only one date being generated (the initial date).
Default Parameter Values
- Concludes with assigning default values during parameter declaration which prevents null checks within the function body when no arguments are passed during calls.
- In a revised version of the date-generating function, two parameters are declared: start date (as before), and number of dates desired. If not specified, it defaults to generating one date only.