PowerShell Language Notes
Getting Started - PowerShell
Variables store a piece of data, such as the results of a command.
The following are some common types of variables:
- Int
: integers like 2
, -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 like 25, "red", $False, 16.30
Variables are referenced using a dollar sign $
.
This syntax indicates that PowerShell is a dynamically typed language.
PowerShell Variables are NOT case-sensitive and can include spaces and special characters when enclosed in curly brackets
{}
.The example uses underscores which are recommended as variables with special characters within their name can be difficult to work with, especially in programs that may require scaling.
When referencing the defined variable into the PowerShell terminal will proceed to Write-Host
the value stored.
The above example will output the -Prompt
string and then wait for the user to input a value. The value will then be stored in the variable named $my_input
.
1) In the PowerShell terminal, create a variable called $pi
and assign it the value 3.14
.
$pi
.$name
and assign your name to it as a string.Read-Host
with the prompt, "Enter your age"
, and save the input to a variable called $age
.Enforcing types, creating multiple variables, and a few variable-related cmdlets.
The following are some common types of variables:
- Int
: integers like 2
, -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 like 25, "red", $False, 16.30
The default type of any uninitialized variable is
$null
.PowerShell uses Dynamic Typing
ps > $($my_string_variable.GetType()).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
False True RuntimeType System.Reflection.TypeInfo
In order to enforce a certain type on a variable, a constrained variable must be created via casting.
ps > [Int]$age = 25
ps > $age
25
ps > $age = "twenty five"
Cannot convert value "twenty five" to type "System.Int32". Error: "Input string was not in a correct format."
PowerShell allows creating multiple variables using one statement.
1) 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
.
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
.
3) Now create three variables using one comma-separated statement.
1. The first variable should be called $name
and initialized to your name in a string format.
2. The second variable should be called $color
and initialized to your favorite color in a string format.
3. The third and final variable should be called $date
and assign (Get-Date).DateTime
to it.
$date_data_type
variable to the data type of the date
variableEnvironmental Variables store information related to the current session such as the Operating System and user sessions like the terminal. Global variables which means they can be easily accessed across commands and programs. Typically created by the OS but can also be utilised to configure the production environment.
Get-ChildItem Env:
Name Value
---- -----
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\USER\AppData\Roaming
CommonProgramFiles C:\Program Files\Common Files
CommonProgramFiles(x86) C:\Program Files (x86)\Common Files
CommonProgramW6432 C:\Program Files\Common Files
---SNIP---
The two most common utilised environmental variables utilised in PowerShell are HOME
and PATH
.
HOME
- Indicates the current user's home directory.
PATH
- Includes all directories where applications look for executables.
1) List all the environment variables using the PowerShell Terminal
Get-ChildItem
- Cmdlet lists all the items in a specific location similar to ls
in Unix-like systems or dir
.
Env:
- The drive containing all the environmental variables showing their names
and values
.
2) Create a new environment variable called USERS
and assign your name as the value. Be sure to use all capital letters.
USERS
in the list.USERS
.environment_variables.ps1
script file in the terminal by typing ./environment_variables.ps1
.ps > ./environmental_variables.ps1
Hello, THE MALEVOLENT ONE!
Name Value
---- -----
BROWSERSLIST_IGNORE_OLD_DATA 1
EIN_IMAGE ubuntu
EXPIRES_AT 1757976864
HOME /home/ccuser
HOSTNAME 1db8d50e334e
LANG en_US.UTF-8
LOG_LEVEL 2
PATH /opt/microsoft/powershell/7:/home/cc…
POWERSHELL_UPDATECHECK Off
PSModulePath /home/ccuser/.local/share/powershell…#
PWD /home/ccuser/workspace/lps-vo4
SESSION_ID 1502cce7-7b73-4376-875b-66ed84fc23b9
TERM xterm
TZ Etc/UTC
USERS THE MALEVOLENT ONE
WORKSPACE_SERVICE_HOST https://workspace.production-eks.cod…
Operator | Name | Description |
---|---|---|
+ | Addition | Adds numbers, concatenates strings and arrays. |
- | Subtraction | Subtracts or negates numbers. |
* | Multiplication | Multiplies numbers or copies strings and arrays a specified number of times. |
/ | Division | Divides numbers. |
% | Modulo | Returns the remainder of a division operation. |
Arithmetic operators are binary operators, which means they act on two operands. Their syntax in PowerShell is
<Operand_1> <Arithmetic Operator> <Operand_2>
.Arithmetic operators,
+
and*
, also work on strings and arrays.
Operator | Name | Description |
---|---|---|
= | Assignment | $x = 3 assigns value 3 to variable x . |
+= | Addition Compound Assignment | $x += 3 is short for $x = $x + 3 . |
-= | Subtraction Compound Assignment | $x -= 3 is short for $x = $x - 3 . |
*= | Multiplication Compound Assignment | $x *= 3 is short for $x = $x * 3 . |
/= | Division Compound Assignment | $x /= 3 is short for $x = $x / 3 . |
%= | Modulo Compound Assignment | $x %= 3 is short for $x = $x % 3 . |
## Unary Operators | ||
Operator | Name | Description |
--- | --- | --- |
++ | Increment | $x++ is short for $x = $x + 1 . |
-- | Decrement | $x-- is short for $x = $x - 1 . |
## Equality Comparison Operators | ||
Operator | Name | Description |
-------- | ----------------------------- | ------------------------------------------------------------- |
-eq | Equal (==) | $x -eq $y is True if x and y are equal. |
-ne | Not Equal (!=) | $x -ne $y is True if x and y are not equal. |
-gt | Greater Than (>) | $x -gt $y is True if x is greater than y . |
-lt | Less Than (<) | $x -lt $y is True if x is less than y . |
-ge | Greater Than or Equal to (>=) | $x -ge $y is True if x is greater than or equal to y . |
-le | Less Than or Equal to (<=) | $x -le $y is True if x is less than or equal to y . |
## Logical Operators | ||
Operator | Name | Description |
--- | --- | --- |
-and | And | $x -and $y is True only if $x and $y are both True . |
-or | Or | $x -or $y is True if either $x or $y is True . |
-xor | Xor | $x -xor $y is True if only, but not both, $x or $y is True . |
! or -not | Not | !$x is True when $x is False and False when $x is True . |
## Operator Precedence | ||
The Operator Precedence is the order of operations in which PowerShell evaluates operators used in the same expression. |
The PowerShell Operator Precedence is:
1) Parentheses ()
2) Unary Operators ++, --
3) Boolean Operators !, not
4) Arithmetic Operators *, /, %, +, -
5) Comparison Operators -eq, -ne, -gt, -ge, -lt, -le
| -contains
-notContains
6) Equality Operators -and, -or, -xor
7) Assignment Operators =, +=, -=, *=, /=, %=
1) In the PowerShell terminal, add two numbers 5
and 2
.
7
from 49
in the terminal."hello"
by 3.64.209
by 3
.39
by 4
.1) In the script file, number_one.ps1
, use the multiplication compound assignment operator to multiply the variable $number
by 3
.
6
to the variable $number
.number
by 3
.$original_number
from the variable $number
.1
from the variable $number
../number_one.ps1
on the terminal to run the script.1) In the PowerShell terminal, check if the string "happy"
is equal to the string "coding"
.
5
is greater than the integer 2
.43.15
is less than or equal to 43.15
.1) In the logical_operators.ps1 script file, check if both variables $number_1
and $number_2
are less than 50
. Assign the Boolean result to a variable called $both_are_less_than_50
.
$number_1
OR $number_2
is greater than 100
. Make the variable $one_is_higher_than_100
equal to its result.$number_1
or $number_2
is less than or equal to 10
and assign the result to a variable $only_one_is_less_than_10
.-not
or !
, verify that the variable $name
is not equal to the string codecademy
. Make the Boolean variable $name_is_not_codecademy
equal to its result../logical_operators.ps1
.1) In the script file named expression_precedence.ps1
, we have three expressions that return 8
, 6
, and False
respectively. These results are not what we are looking for. Let’s use parentheses ( )
to acquire the desired results.
For expression_1
, we want 4
as a result. Put parentheses around the expression 2 + 4 * 2
.
2
to be the result of expression_2
. Enclose the expression 3 * (2 + 1)
with parenthesesexpression_3
is currently returning False
. We want this to be True
. Remove parentheses around 3 + 2 -ne 5
and put parentheses around 2 -ne 5
instead. Remove parentheses around 5 -gt 8
and put parenthesis around the -gt
operator expression 2 * 5 -gt 8
.
Current Progression:
- How to create variables in a variety of ways
- Variable types and constrained variables
- Listing and creating environment variables
- Manipulate variables and data with operators
- Using arithmetic operators
- Using assignment and unary operators to change data
- Using equality and type comparison operators to compare two pieces of data
- Using logical operators that enable us to create complex comparison statements
- Order of operation
[[Objects & Arrays - PowerShell]]