Giving our functions some data to perform the correct task is often helpful. To send data with our function call, we use parameters.
Let’s say when we greet someone, we would like to use their name:
function greet1 { param($name) Write-Host "Hello, $name" }
Within the above function greet1
, we have added the line param($name)
. This allows the function to receive data from our function call and place it in the variable $name
.
greet1 "Codecademy" # outputs "Hello, Codecademy"
By adding a string to our function call, we now pass "Codecademy"
to the variable $name
in the greet1
function.
We can also pass multiple variables by separating parameters by commas in the function:
function greet2 { param($timeOfDay, $name) Write-Host "Good $timeOfDay, $name" }
The function greet2
is now crafting its greeting using 2 variables, $timeOfDay
and $name
.
To call this function, separate the data by spaces after the function call:
greet2 "Evening" "Codecademy" # outputs "Good Evening, Codecademy"
Parameters allow us to change the behaviors of our functions. This supports their purpose of being able to reuse code in multiple places that may each night need slightly different behavior.
Instructions
The example in the previous exercise provided positive user feedback, but it would be very repetitive to use the same message over and over. Let’s add parameters to the function so that we can pass a username and percentage to the function.
Start by adding a line at the beginning of the function so that the function accepts two parameters, $UserName
and $PercentComplete
.
Add a Write-Host
line to output a string with the $UserName
parameter. An example string is:
"You're doing great, $UserName!"
Add another Write-Host
line to output a string with the $PercentComplete
parameter. An example string is:
"You're $PercentComplete% done!"
Test out the function by adding a function call with your name and a percentage amount.