Looping is a common programming concept used in PowerShell scripts to repeat a block of code mulitple times. It is the beauty of programming language.
PowerShell provides three loop functions, for, foreach, while.
[Loop]
For
The For loop function is used to iterate through a fixed number of times. The syntax of the For loop is as follows:
for ($i=0; $i -lt 10; $i++) {
# Code to be repeated goes here
}
For example,
# Exmaple of loop functions in PowerShell:Multiplication table
# For loop
$Dan = 2
for($i=1; $i -le 9; $i++)
{
Write-Host $Dan X $i = $dan*$i
}
2 X 1 = 2*1
2 X 2 = 2*2
2 X 3 = 2*3
2 X 4 = 2*4
2 X 5 = 2*5
2 X 6 = 2*6
2 X 7 = 2*7
2 X 8 = 2*8
2 X 9 = 2*9
ForEach
The ForEach loop function is used to iterate through a collection of items, such as an array or a list. The syntax of the ForEach loop is as follows:
foreach ($item in $collection) {
# Code to be repeated goes here
}
For example,
# Exmaple of loop functions in PowerShell:Multiplication table
# foreach
$Dan = 2
$times = 1,2,3,4,5,6,7,8,9
foreach($time in $times)
{
Write-Host $dan X $time = $dan*$time
}
2 X 1 = 2*1
2 X 2 = 2*2
2 X 3 = 2*3
2 X 4 = 2*4
2 X 5 = 2*5
2 X 6 = 2*6
2 X 7 = 2*7
2 X 8 = 2*8
2 X 9 = 2*9
While
While loop: The While loop function is used to iterate through a block of code while a condition is true. The syntax of the While loop is as follows:
while ($condition) {
# Code to be repeated goes here
}
For example,
# Exmaple of loop functions in PowerShell:Multiplication table
# while
$Dan = 2
$times = 1
while($times -le 9)
{
Write-Host $Dan X $times = $Dan*$times
$times++
}
2 X 1 = 2*1
2 X 2 = 2*2
2 X 3 = 2*3
2 X 4 = 2*4
2 X 5 = 2*5
2 X 6 = 2*6
2 X 7 = 2*7
2 X 8 = 2*8
2 X 9 = 2*9
반응형
'ICT' 카테고리의 다른 글
[PowerShell]Creating Email Distribution Group (0) | 2023.04.04 |
---|---|
[PowerShell]7. Functions (0) | 2023.04.03 |
[PowerShell]Checking User EmailBox Storage Status (0) | 2023.03.30 |
[PowerShell]5. Controls(If statement) (0) | 2023.03.28 |
[PowerShell]4. Variables(variable converting) (1) | 2023.03.27 |
댓글