PowerShell: The basics – Part 3 – Data Types, Variables, Operators, and Functions

This blog series will teach you the basics of PowerShell. You’ll learn common concepts such as variables, loops, functions and scripts in this series, along with PowerShell unique concepts such as cmdlets and the pipeline.

In this post we will take a brief look at data types, variables, operators, and functions.

Data types

All data in PowerShell has a data type, but you don’t often have to deal with it as PowerShell usually handles the data types and conversion automatically in the background. Nonetheless, here are the most common data types in PowerShell:

NameValues
ArrayA list of values of any data type, even other arrays
BoolValue is True or False
DateTimeDate and time
Guid Globally unique 32-byte identifier
HashTable Hash table, collection of key-value pairs
Int32, Int32-bit Integer (-2147483648 to 2147483647)
Long64-bit Integer
PSObjectPowerShell Object
ScriptBlock A PowerShell scriptblock
Single32-bit floating point number
Double64-bit floating point number
StringString (Text object)
Char16-bit character
Byte8-bit character
Switch Switch parameter

One can easily determing the data type by piping the data to the cmdlet Get-Member:

Another way to find the type by invoking the objects GetType() method.

"Hello".GetType().FullName

You can also manually specify the data type, by wrapping the type in square brackets and specifying it before the value, or before the variable assignment.

[DateTime]$Date = "July 18, 2019"
[bool]$Truth = 0
$Count = [Int]'12'

Variables

Text, data or objects can all be stored in what’s called variables. In PowerShell variables are prefixed with a dollar sign $, and then the name of the variable. I.e. $myVariable, or $username.
Best practice dictates that variables should have clear, meaningful names, to describe their contents.

In many languages you have to declare the data type a variable can hold, but PowerShell is very forgiving and doesn’t require this. Note that it is still best practice when working with functions and parameters, more on that later.

# Assign a string value to a new variable
$name = 'Martin'

# Append a string to the variable
$name += ' Norlunn'

# Prepend a string to the variable
$name = "Mr. $name"

# Use the variable
Write-Host "My name is $name"

# Assign an integer value to a new variable
$age = 2 + 3

# Increment value by 1
$age += 1

# Use the variable
Write-Host "I am $age years old"

# View all properties and methods related to the string object
$name | Get-Member

# Calling the ToUpper method will print the string in upper case only
$name.ToUpper()

Note: When using a variable in a string you must use double quotes for PowerShell to parse the variable.
A variable can also hold an array of data:

# Declare an array that holds three string values
$myColors = 'red', 'blue', 'yellow'
 
# Display contents of array
$myColors
 
# Display only the first element
$myColors[0]
# or
$myColors | Select-Object -First 1

Automatic variables

Some variable names are reserved and are automatically populated with data by PowerShell.

VariableDescription
$? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.
$$Contains the last cmdlet in the previous line
$^ Contains the first cmdlet in the previous line
$_ / $PSItem Contains the current object in the pipeline object
$args Contains an array of values for undeclared parameters that are passed to a function, script, or script block.
$false / $trueContains FALSE/TRUE values
$MatchesValues that match against the -Match or -Notmatch operators are automatically populated in this variable
$null$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
$pidContains the process identifier (PID) of the process that is hosting the current PowerShell session.
$profileContains the full path of the PowerShell profile for the current user and the current host application.
$PSBoundParameterValues Contains a dictionary of the parameters that are passed to a script or function and their current values.
$PSScriptRootContains the directory from which a script is being run
$PSVersionTableContains a read-only hash table that displays details about the version of PowerShell that is running in the current session
$pwd Contains a path object that represents the full path of the current directory

Arithmetic Operators

Arithmetic Operators calculate numeric values. This behaves the same in most languages and is based on normal math. The most common operators are + (addition), – (subtraction), * (multiplication), / (division), and % (modulus).

What’s a bit different is that some of these can be used on strings and arrays. You can use + to merge two strings/arrays, and * to repeat the string/array multiple times.

"!" * 5
@(1, 2, 3) * 5

Assigment Operators

Assignment operators assign one or more values to a variable. They can perform numeric operations on the values before the assignment.

Operator Description
= Sets the value of a variable to the specified value
+=Increases the value of a variable by the specified value, or appends the specified value to the existing value
-=Decreases the value of a variable by the specified value
*=Multiplies the value of a variable by the specified value, or appends the specified value to the existing value
/=Divides the value of a variable by the specified value
%=Divides the value of a variable by the specified value and then assigns the remainder (modulus)
++Increases the value of a variable, assignable property, or array element by 1
Decreases the value of a variable, assignable property, or array element by 1

Comparison Operators

Comparison operators is a mean to compare two values. This is a common concept in all languages, but PowerShell’s syntax differs quite a bit. An expression with two values and an operator, evaluates to either true or false boolean values.

# Check if values are equal
50 -eq 50 # Evaluates to true

# Check if value is greater than
60 -gt 40 # Evaluates to true

# Check if values is less than or equal to
40 -le 40 # Evaluate sto true

# Check if value is present in array of values
50 -in 40, 50, 60 # Evaluates to true

# Check if value is not present in array of values
50 -notin 40, 50, 60 # Evaluates to false

# Wildcard match on string: Ends with Shell
'PowerShell' -like "*Shell" # Evaluates to true

Comparison operators are often used in if statements or in filter scripts. You can find a list of all operators here:
About Comparison Operators

Logical Operators

Logical operators connects multiple statements into a single expression.

OperatorDescription
-andEvaluates to true when both statements are true
-orEvaluates to true when either statement is true
-xorEvaluates to true if only one of the statements are true
-notNegates the following statement
!Same as -not
(1 -eq 1) -and (1 -eq 2) # False
(1 -eq 1) -or (1 -eq 2) # True
(1 -eq 1) -xor (2 -eq 2) # False
-not (1 -eq 1) # False
!(1 -eq 1) # False

Functions

A function is list of PowerShell statements to which you assign a name. A function can take input, and produce output. You can call on your function from where you want, and however many times you want. Functions are great for refactoring your code, that is not having to type the same logic over and over again.

# A basic function
Function Square
{
    Param([Int]$Value)
    $Value * $Value
}

# Calling on the function with a value, and storing the output in a new variable
$newValue = Square -Value 25

# Calling it again, overwriting the variable
$newValue = Square -Value 20

# Display the output
$newValue

# This also works, but is not best practice. It's called positional parameters.
$newValue = Square 20

In other languages you have to specify the Return keyword to return a value from a function, but in PowerShell, everything is by default returned. It’s because behind the scenes PowerShell calls Write-Ouput on the value when no other cmdlets are specified.
Also note that I have specified the value type in the function parameter, this is best practice so to ensure nobody passes data type that will break the function.

Functions should be quite specific in which task they complete, and should not be very large. Large functions can often be broken apart into multiple functions, and you can call on one function from another function just fine.

Further reading

In the next post we’ll take a look at strings, arrays, hashtables, conditional statements, and loops. If you want more detailed reading on the topics of this post I suggest the following resources: