In this exercise, we will discuss how variable types are handled in PowerShell and a few advanced ways to interact with variables, including enforcing types, creating multiple variables, and a few variable-related cmdlets.
Variable Types
The following are some common types of variables:
Int
: integers like2
,-5
,99
String
: zero or more characters enclosed in double quotes like"Codecademy!"
,"3X4mP|3"
Boolean
: two possible values:$True
and$False
Array
: a collection of items like25, "red", $False, 16.30
PowerShell assigns a type to the variable depending on the value we assign to it. This is called dynamic typing. The default type of any uninitialized variable is $null
.
We can append .GetType().Name
to the variable reference to determine a variable’s data type.
PS > $my_string_variable = "Hello, World!" PS > $my_string_variable.GetType().Name String
In the example above, we are accessing the Name
property of the GetType()
method of a variable we initialized.
- The
GetType()
method returns the name and base type property for a variable - Accessing the
Name
property only returns the data type we desire - The variable’s data type is
String
Constrained Variables
If we wish to enforce a certain type on a variable, we can create a constrained variable via casting.
PS > [Int]$age = 25 PS > $age 25 PS > [Int]$age = "twenty five" Cannot convert value "age" to type "System.Int32". Error: "Input string was not in a correct format."
When initializing a variable, we specify the type in brackets before referencing the variable. Attempting to assign a value of another type results in an error if PowerShell cannot convert it.
Create Multiple Variables
PowerShell allows us to create multiple variables using one statement. To initialize multiple variables with the same value,
$i = $j = $k = 0
To assign multiple values to multiple variables,
$number, $color, $bool = 25, "red", $false
We will next discuss a specific type of variable called an environment variable.
Instructions
At the top of the variable_types.ps1 file, create a constrained variable of type Int
and the name $num_1
. Assign $num_1
the value 42
.
Click Run when you are done.
Create another constrained variable in the the variable_types.ps1 file of type Int
and the name $num_2
. Give $num_2
the value "forty two"
.
You will encounter an error, but it works as intended! Data of String
type cannot be assigned to a variable expecting an Int
.
Click Run when you are done.
Now create three variables using one comma-separated statement.
- The first variable should be called
$name
and initialized to your name in a string format. - The second variable should be called
$color
and initialized to your favorite color in a string format. - The third and final variable should be called
$date
and assign(Get-Date).DateTime
to it.
Click Run when you are done.
Initialize the $date_data_type
variable to the data type of the date
variable and click Run.