Course Overview

/

Powershell Function

Powershell Functions

In PowerShell, a function is defined by using the keyword function and then the function name the code to be used is then encapsulated with {} characters. There is no need to indent the code, however it is best practice to do so as it makes reading the script much easier.

One of the benefits to using functions is the ability to write code once and call it in multiple locations throughout a script. It is also possible to combine functions together to create more advanced actions without having to add too much complexity to the scripting process.

2nd PowerShell Script

The second PowerShell script created is:

These functions provide a small block of code to conduct an action with the variables provided.

Function 1

Function 1 is a simple function that declares the x and y variables and shows 2 methods to print the output of x multiplied by y to the command line. Note the use of the command

to declare the function, and the closing brace (}) to end the function

Function 2

Function to introduces a parameter called name that the function will need when being executed and will be used as part of the output

As this parameter is a string, the text “Dan” is encapsulated in quotation marks. The Write-Output command acts like a Python formatted string and can have the parameter used within the string value

Function 3

Demonstrates that multiple parameters can be passed to a function with ease. All parameters need to be defined when creating the function,

and can then be provided when executing the functionBy introducing functions into a script it is possible to create small sections of code that perform a specific task. Functions are used to make code more modular, easier to read, and easier to reuse. By dividing a program into smaller, independent functions, it becomes easier to understand and maintain the program as a whole.

2nd Powershell Script

2nd PowerShell Script

The second PowerShell script created is:

#powershell script to look at functions #function with no parameter function function1 { $x =2 $y = 4 Write-Output ($x *$y) Write-Host ($x * $y) } function1 #function with 1 parameter function function2($name) { Write-Output "Hello $name, you are learning PowerShell Scripting" } function2 "Dan" #function with 2 parameter function function3($x, $y) { Write-Output ($x + $y) } function3 3 12

These functions provide a small block of code to conduct an action with the variables provided.