As you develop scripts, you will likely write similar lines repeatedly. Instead of constantly typing or copying the same lines, it’s best practice to write a function containing those lines.

Functions are a way to collect code in a single space and reference them with a simple command throughout your script. This makes code easier to read.

function greet { Write-Host "Hello, there!" }

The above function is named greet and contains one line of code that outputs a hello message. Within our code, we can now “call” the function by its name, greet.

If we use the greet function multiple times in our code and decide to change our greeting from "Hello there!" to "Hi", we only have to change it once; inside the greet function.

We also have a useful code block to take to other scripts. If another script needs to output a greeting, we can copy the function over and reference it in our code.

Functions are an excellent programming practice because:

  • Whenever a collection of code is needed, it can be called via a single reference, which will make our code cleaner and easier to read.
  • If changes are needed to any parts of those lines of code, we can adjust it in a single location rather than multiple locations.
  • Reuse! If we’ve written code for one script, there’s a good chance we might need it for another. Well-designed functions can be used across multiple scripts.



Within an existing script is a function called VacationPicker. This function contains an array with some vacation destinations, and a cmdlet that selects an item from the array at random. Since you can never decide where to go, you want to use this function to decide for you!!

Add a line to call the function (And find out what kind of trip you’ll be taking!)

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?