0
0
PowerShellscripting~10 mins

ForEach loop in PowerShell - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to loop through each item in the array and print it.

PowerShell
foreach ($item [1] $array) { Write-Output $item }
Drag options to blanks, or click blank then click option'
Aof
Bon
Cin
Dat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'of' or 'on' instead of 'in' causes syntax errors.
Leaving out the keyword entirely.
2fill in blank
medium

Complete the code to loop through numbers 1 to 5 and print each number.

PowerShell
foreach ($num [1] 1..5) { Write-Output $num }
Drag options to blanks, or click blank then click option'
Ain
Bfrom
Con
Dof
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'from' or 'of' instead of 'in' causes errors.
Trying to use a comma-separated list without the range operator.
3fill in blank
hard

Fix the error in the loop to correctly print each name in the list.

PowerShell
$names = @('Anna', 'Bob', 'Cara')
foreach ($name [1] $names) { Write-Output $name }
Drag options to blanks, or click blank then click option'
Ain
Bon
Cat
Dof
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'on' or 'of' causes the loop to fail.
Forgetting the keyword entirely.
4fill in blank
hard

Fill both blanks to create a loop that prints only even numbers from 1 to 10.

PowerShell
foreach ($num [1] 1..10) { if ($num [2] 2 -eq 0) { Write-Output $num } }
Drag options to blanks, or click blank then click option'
Ain
B%
C==
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '%' for checking even numbers.
Using 'on' instead of 'in' for the loop.
5fill in blank
hard

Fill all three blanks to create a dictionary of word lengths for words longer than 3 characters.

PowerShell
$words = @('cat', 'house', 'tree', 'a', 'dog')
$lengths = @{}
foreach ($word [1] $words) { if ($word.Length [2] 3) { $lengths[[3]] = $word.Length } }
$lengths
Drag options to blanks, or click blank then click option'
Ain
B>
C$word
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for length comparison.
Using the wrong key for the dictionary.