본문 바로가기
ICT

[PowerShell]6. Loops

by NeoSailer 2023. 3. 30.

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

 

반응형

댓글