Skip to content

Commit 54fcf73

Browse files
jacevanPrince25
andauthored
Merge Powershell Topic form PowerShell-Jace branch to main (Codecademy#2185)
* PowerShell: Initial file push (Codecademy#1673) * Initial PowerShell file structure commit * Fixed powershell.md error * Run format script --------- * Add Arrays, Objects, Operators, Variables content for PowerShell (Codecademy#1705) * Add arrays, objects, operators, variables content for PowerShell * Apply suggestions from code review for PowerShell Arrays * Apply suggestions from code review for PowerShell Objects * Apply suggestions from code review for PowerShell Operators * Apply suggestions from code review for PowerShell Varaibles * Apply suggestions from PowerShell code review * Update metadata (catalog and tags) for PowerShell - Add tags: Assignment, Environment Variables, Equality, Precedence, Unary - Add PowerShell to catalog - Reorder and add tags to content metadata * Apply suggestions from PowerShell code review Change 'PowerShell' to 'Bash/Shell' under subjects. * Change code blocks, subject, and add examples on PowerShell concepts - Change PowerShell code blocks to shell code blocks - Change 'PowerShell' subject to 'Bash/Shell' - Add examples to Operators * Apply suggestions from PowerShell code review * Apply suggestions from PowerShell code review * Apply suggestions from PowerShell code review Co-authored-by: jacevan <[email protected]> * Apply feedback changes from PowerShell code review - Remove Environment Variables from Variables Doc - Add Environment Variable Doc - Other Feedback Changes Co-Authored-By: jacevan <[email protected]> * Ensure PowerShell boolean are capitalized Co-Authored-By: jacevan <[email protected]> * Make minor formatting changes to PowerShell docs * prettier formatting --------- Co-authored-by: jacevan <[email protected]> * Add PowerShell content: Conditionals, Functions, and Loops (Codecademy#1794) * Add PowerShell content: Conditionals, Functions, and Loops - Add Conditionals, Functions, and Loops docs for PowerShell - Add tags: Break, Continue, ForEach * Apply suggestions from PowerShell Conditionals code review * Apply suggestions from PowerShell code review Co-authored-by: jacevan <[email protected]> * Apply feedback changes from PowerShell code review Co-Authored-By: jacevan <[email protected]> * Add break example to PowerShell Conditionals doc Co-Authored-By: jacevan <[email protected]> * Apply suggestions from PowerShell code review * prettier formatting --------- Co-authored-by: jacevan <[email protected]> * Update powershell main page * Update powershell.md * Updated powershell.md description and content (Codecademy#2112) * Update powershell main page * Update powershell.md --------- * Check for format --------- Co-authored-by: Prabhjot Singh <[email protected]>
1 parent 50637ff commit 54fcf73

File tree

11 files changed

+1067
-0
lines changed

11 files changed

+1067
-0
lines changed
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
---
2+
Title: 'Arrays'
3+
Description: 'Arrays are a data structure that holds a collection of items. PowerShell provides many ways to access, update, and manipulate array items.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
- 'Bash/Shell'
8+
Tags:
9+
- 'Arrays'
10+
- 'Data Types'
11+
- 'Data Structures'
12+
- 'Index'
13+
- 'Lists'
14+
- 'Operators'
15+
- 'Variable Types'
16+
CatalogContent:
17+
- 'learn-powershell'
18+
- 'paths/computer-science'
19+
---
20+
21+
**Arrays** are a [data structure](https://www.codecademy.com/resources/docs/general/data-structures) that holds a collection of items. Items can be of the same type or multiple types.
22+
23+
## Creating an Array
24+
25+
Separating items by commas (`,`) is the simplest way to create an array in PowerShell.
26+
27+
```shell
28+
$my_arr = 25, "Codecademy", 1, $False
29+
```
30+
31+
Alternatively, the array subexpression operator `@( )` can be used. Anything placed within the parentheses is treated as an item of the array.
32+
33+
```shell
34+
$arr_1 = @($True, 5, (Get-Date).DateTime) # 3 elements
35+
$arr_2 = @( ) # Empty Array
36+
$arr_3 = @( # Multi-line Array
37+
"Uno"
38+
"Dos"
39+
"Tres"
40+
)
41+
```
42+
43+
## Accessing Array Items
44+
45+
The items in an array are accessed using their index, or their position in the array. Consider the array:
46+
47+
```shell
48+
$colors = "red", "yellow", "black", "blue"
49+
```
50+
51+
The indexes in PowerShell start at `0`.
52+
53+
| Index | Value |
54+
| :---: | :--------: |
55+
| `0` | `"red"` |
56+
| `1` | `"yellow"` |
57+
| `2` | `"black"` |
58+
| `3` | `"blue"` |
59+
60+
Brackets `[ ]` are used to access an item in an array. To access `"black"` in the `$colors` array, for example:
61+
62+
```shell
63+
PS > $colors[2]
64+
black
65+
```
66+
67+
## Updating Array Items
68+
69+
Items can be updated — or changed – by utilizing indexes. To change the color `yellow` to `brown`, for example:
70+
71+
```shell
72+
PS > $colors[1] = "brown"
73+
PS > $colors
74+
red
75+
brown
76+
black
77+
blue
78+
```
79+
80+
## Indexing
81+
82+
PowerShell offers flexibility when indexing items, such as:
83+
84+
- Multiple indexes: Separate indexes with commas to print multiple items.
85+
86+
```shell
87+
PS > $colors[0,2]
88+
red
89+
black
90+
```
91+
92+
- Range operator `..`: Print all items between two indexes (exclusive).
93+
94+
> **Note:** This syntax is exclusive since the stop index `3` is not included.
95+
96+
```shell
97+
PS > $colors[1..3]
98+
brown
99+
black
100+
blue
101+
```
102+
103+
- Reverse range: Use range operator from a higher index to a lower index to print items in reverse order (inclusive).
104+
105+
> **Note:** This syntax is inclusive since both the start and stop indexes, `2` and `1`, are included.
106+
107+
```shell
108+
PS > $colors[2..1]
109+
black
110+
brown
111+
```
112+
113+
- Negative indexes: Items are referenced in reverse order where the last item has an index of `-1`.
114+
115+
```shell
116+
PS > $colors[-1]
117+
blue
118+
```
119+
120+
## Iteration
121+
122+
Each array object has a method called `ForEach` which can be utilized to perform the same action on each of its items. PowerShell defines the variable `$PSItem` or just underscore `_` to refer to each item in the array.
123+
124+
```shell
125+
PS > $colors.ForEach({ $PSItem.Length }) # $_.Length also works
126+
3
127+
5
128+
5
129+
4
130+
```
131+
132+
The example above is printing the length of each string of our `colors` array. `red` has a length of `3`, `brown` is `5`, and so on.
133+
134+
## Array Operators
135+
136+
### Addition Operator
137+
138+
The addition operator `+` concatenates – or combines – two arrays.
139+
140+
```shell
141+
PS > $fibonacci_1 = 0, 1, 1
142+
PS > $fibonacci_2 = 2, 3, 5
143+
PS > $fibonacci_1 + $fibonacci_2
144+
0
145+
1
146+
1
147+
2
148+
3
149+
5
150+
```
151+
152+
### Multiplication Operator
153+
154+
The multiplication operator `*` copies the array a specified number of times.
155+
156+
```shell
157+
PS > $fibonacci_2 * 2
158+
2
159+
3
160+
5
161+
2
162+
3
163+
5
164+
```
165+
166+
### Containment Operators
167+
168+
Containment operators check whether or not an item is in an array and returns a boolean.
169+
170+
| Operator | Syntax | Example |
171+
| :------------: | :---------------------------: | :-----------------------------------------: |
172+
| `-contains` | `<array> -contains <item>` | `$fibonacci -contains 4` returns `False`. |
173+
| `-notcontains` | `<array> -notcontains <item>` | `$fibonacci -notcontains 4` returns `True`. |
174+
| `-in` | `<item> -in <array>` | `5 -in $fibonacci` returns `True`. |
175+
| `-notin` | `<item> -notin <array>` | `5 -notin $fibonacci` returns `False`. |
176+
177+
### `-join`
178+
179+
The `-join` operator combines the items in an array into a string separated by a character or a string. Consider the following example:
180+
181+
```shell
182+
PS > $fibonacci = 0, 1, 1, 2, 3, 5
183+
PS > $fibonacci = $fibonacci -join "->"
184+
PS > $fibonacci
185+
0->1->1->2->3->5
186+
PS > $fibonacci.GetType().Name
187+
String
188+
```
189+
190+
## Strongly Typed Arrays
191+
192+
Types can be casted onto arrays to force each item in the array to adhere to that type.
193+
194+
```shell
195+
PS > [String[]]$fruits = "apple", "banana", "kiwi"
196+
```
197+
198+
## Objects Arrays
199+
200+
Arrays can hold objects.
201+
202+
```shell
203+
$dogs_arr = @(
204+
[PSCustomObject]@{Name = 'Rufus'; Age = 10}
205+
[PSCustomObject]@{Name = 'Miku'; Age = 2}
206+
)
207+
```
208+
209+
Each object in the array as well as its properties and methods can be accessed individually.
210+
211+
```shell
212+
PS > $dogs_arr.ForEach({ $PSItem.Name + " is " + $PSItem.Age + " years old."})
213+
Rufus is 10 years old.
214+
Miku is 2 years old.
215+
```
216+
217+
> **Note:** `$PSItem` can be replaced with its shorthand alias `$_`.
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
---
2+
Title: 'Conditionals'
3+
Description: 'The if, else, elseif, and switch conditionals in PowerShell are used for control flow. They allow the choice of which sections of code are executed based on conditions.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
- 'Bash/Shell'
8+
Tags:
9+
- 'Break'
10+
- 'Conditionals'
11+
- 'Control Flow'
12+
- 'Else'
13+
- 'If'
14+
- 'Switch'
15+
CatalogContent:
16+
- 'learn-powershell'
17+
- 'paths/computer-science'
18+
---
19+
20+
**Conditionals** enable execution of code based on provided conditions. They take in an expression and check if it is `True` or `False`. If the expression is `True`, one set of statements is executed. Otherwise, another set of instructions is performed. This control of flow makes programs more robust by enabling them to address multiple scenarios.
21+
22+
There are four types of conditional statements in PowerShell:
23+
24+
1. `if`
25+
2. `else`
26+
3. `elseif`
27+
4. `switch`
28+
29+
## if
30+
31+
The `if` statement executes a block of code if the condition expression is `True`.
32+
33+
```shell
34+
$my_num = 2
35+
if($my_num -eq 2){
36+
Write-Host "A True Statement"
37+
}
38+
Write-Host "After the if statement"
39+
```
40+
41+
The example above prints `"A True Statement"` and `"After the if statement"` if `$my_num` is equal to `2`. Otherwise, it skips the statement within the `if` curly braces `{ }` and just prints `"After the if statement"`.
42+
43+
## else
44+
45+
The `else` clause always follows the `if` statement.
46+
47+
- If the condition is `True`, the code in the `if` section is executed.
48+
- If the condition is `False`, the code in the `else` section is executed.
49+
50+
```shell
51+
$my_num = 2
52+
if($my_num -gt 0) {
53+
Write-Host "A positive number" # Prints if $my_num is more than 0
54+
}
55+
else {
56+
Write-Host "A negative number" # Prints if $my_num is less than or equal to 0
57+
}
58+
```
59+
60+
## elseif
61+
62+
One or more `elseif` statements can be added between `if` and `else` to test multiple conditions.
63+
64+
```shell
65+
$my_num = 2
66+
if($my_num -gt 0) {
67+
Write-Host "A positive number" # Prints if $my_num is more than 0
68+
}
69+
elseif ($my_num -lt 0) {
70+
Write-Host "A negative number" # Prints if $my_num is less than 0
71+
}
72+
else {
73+
Write-Host "Zero" # Prints if both of the previous conditions fail
74+
}
75+
```
76+
77+
## switch
78+
79+
The `switch` statement provides a simpler syntax for the same behavior as `if` / `elseif` expressions that check for equality.
80+
81+
```shell
82+
$my_num = 2
83+
switch ($my_num) {
84+
1 {
85+
Write-Host "You chose 1"
86+
}
87+
2 {
88+
Write-Host "You chose 2"
89+
}
90+
3 {
91+
Write-Host "You chose 3"
92+
}
93+
default {
94+
Write-Host "No match"
95+
}
96+
}
97+
```
98+
99+
The example above prints `"You chose 2"`. If `$my_num` was `4`, for example, it would print `"No match"` since the `default` clause is run if all other conditions fail.
100+
101+
PowerShell allows conditional expressions to be used in `switch` statements.
102+
103+
```shell
104+
$my_num = 10
105+
switch ($my_num) {
106+
{$PSItem -gt 5} {
107+
Write-Host "Greater than 5"
108+
}
109+
{$PSItem -gt 0} {
110+
Write-Host "Greater than 0"
111+
}
112+
{$PSItem -lt 5} {
113+
Write-Host "Less than 5"
114+
}
115+
}
116+
```
117+
118+
> **Note:** `$PSItem` is an automatic variable that contains the value passed to the `switch` statement. It can be replaced with its shorthand alias `$_`.
119+
120+
The above example prints `"Greater than 5"` and `"Greater than 0"` since their corresponding conditions are `True`. Even if a condition is `True`, the following conditions are still tested unless a `break` statement is provided, as in the example below which only prints `"Greater than 5"`.
121+
122+
```shell
123+
$my_num = 10
124+
switch ($my_num) {
125+
{$_ -gt 5} {
126+
Write-Host "Greater than 5"
127+
break
128+
}
129+
{$_ -gt 0} {
130+
Write-Host "Greater than 0"
131+
}
132+
{$_ -lt 5} {
133+
Write-Host "Less than 5"
134+
}
135+
}
136+
```

0 commit comments

Comments
 (0)