A server administrator is writing a PowerShell script to automate a daily health check for a list of application servers. The script needs to iterate through a predefined list of server names and test the network connection to each one. Which of the following script constructs should the administrator use to accomplish the repetitive task of checking each server in the list?
A $variable = Read-Host command to prompt for each server name manually.
A foreach loop to iterate through the array of server names.
An if-else statement to evaluate the connection status of a single server.
A switch statement to handle different actions based on server roles.
The correct answer is a foreach loop. In PowerShell, the foreach statement is explicitly designed to iterate over each element in a collection-such as an array of server names-and execute the same block of code for every item, which is exactly what this automation requires.
A switch statement can also receive a collection and will evaluate every element, but it is intended for branching logic where different actions are performed depending on which condition matches, not for performing the same action on all items. An if-else construct evaluates a single condition only once and does not automatically repeat, and the Read-Host cmdlet pauses the script to request interactive input, defeating the purpose of unattended automation.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What is a `foreach` loop in PowerShell?
Open an interactive chat with Bash
How does a `switch` statement differ from a `foreach` loop?
Open an interactive chat with Bash
Why is `Read-Host` not ideal for scripting automation?