Learn

Let’s start by discussing how variables work. In computer programming, variables are used to store a piece of data. In PowerShell, variables can store the results of commands and expressions like values, names, paths, and settings.

Create a Variable

To create a variable, we must assign it a value. Variables in PowerShell are referenced using a dollar sign $ followed by a variable name. After a variable reference, we use an equal sign = followed by the value we’d like to assign to that variable.

$my_string_variable = "Hello, World!"

In the example above, we are initializing a variable called my_string_variable to a string value of Hello, World!.

Variables names consist of alphanumeric characters. They are NOT case-sensitive and can include spaces and special characters when enclosed in curly braces, {}. However, following the convention of using only alphanumeric characters and the underscore _ character is recommended because variables with special characters in their name are difficult to use.

Use a Variable

PS > $my_string_variable Hello, World!

Variable reference allows us to use or manipulate variables. As shown above, referencing the variable my_string_variable we defined earlier in the PowerShell terminal prints the value we assigned to it.

User Input

Now that we can hold data using variables, we can look at a useful command that enables user input through the terminal.

PS > $my_input = Read-Host -Prompt "Enter a number"

The above example will output the -Prompt string and then wait for the user to input a value and hit Enter. The value will then be stored in $my_input for use later.

These a just a few ways we can use variables to collect, process, and output data within our terminal and scripts.

Instructions

1.

The exercises in this lesson use the Check Work button with the terminal. Perform the tasks and click the Check Work button to move through the instructions. You can advance to the next task or exercise if you accomplish the task correctly.

In the PowerShell terminal, create a variable called $pi and assign it the value 3.14.

Click the Check Work button to continue.

2.

Print the value of the variable called $pi.

3.

Create a variable called $name and assign your name to it as a string.

Note: The string must be enclosed by double quotes ". For example, "Codecademy".

Click the Check Work button to continue.

4.

Use Read-Host with the prompt, "Enter your age", and save the input to a variable called $age.

When prompted for the input, enter your age and press Enter.

5.

Copy and paste the following command on the PowerShell terminal.

Write-Host "Hello, $name! You are $age years old."

Note that the string is enclosed by double quotes ".

Click the Check Work button to continue.

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?