-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6_Loops.ps1
83 lines (64 loc) · 2.38 KB
/
6_Loops.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -------------------------------------------------------
# Loops
# -------------------------------------------------------
# Loops allow you to repeat blocks of code
# While - Code repeats while condition is True
# Do Until - Code repeats until condition is True
# Do While - Code repeats while condition is True
# For - Code repeats a number of times
# Foreach - Code repeats for each item in collection
# ForEach-Object - Code repeats for each object passed in pipeline
# -------------------------------------------------------
# DO vs WHILE
# -------------------------------------------------------
# DO runs code at least once before checking the condition
# WHILE checks condition and then runs code if True
$sample = 2
do {
$sample++ # <- ++ is shorthand for $sample = $sample + 1
Write-Output "Do Loop Ran"
}while($sample -eq 1)
while($sample -eq 2) {
Write-Output "While Loop Ran"
$sample++
}
while($sample -gt 1 -and $sample -lt 10 ) {
Write-Output "While Loop Ran for sample #$($sample)"
$sample++
}
$sample = 1
do {
$sample++ # <- ++ is shorthand for $sample = $sample + 1
Write-Output "Do Loop Ran, Sample is $($sample)"
}until($sample -eq 10)
# -------------------------------------------------------
# For
# -------------------------------------------------------
# For loop will repeat a number of times
for($counter = 0;$counter -le 10;$counter++) {
Write-Output "For Loop Ran, counter is $($counter)"
}
$colors = "Red", "Blue", "Green"
for($counter = 0;$counter -lt $colors.Count;$counter++) {
Write-Output "Counter is $($counter) and color is $($colors[$counter])"
}
# -------------------------------------------------------
# Foreach
# -------------------------------------------------------
# Code repeats for each item in collection
$colors = "Red", "Green", "Blue"
foreach($bob in $colors) {
Write-Output "Current color is $($bob)"
}
# -------------------------------------------------------
# ForEach-Object
# -------------------------------------------------------
# Code repeats for each object passed in pipeline
# $_ represents the current object in the iteration
$colors = "Red", "Green", "Blue"
$colors | ForEach-Object {
Write-Output "Current color is $($_)"
}
(0..$colors.Count) | ForEach-Object {
Write-Output "Current colors is $($colors[$_])"
}