If you know the exact number of loops you can use for loops, the For loop belongs to the counting loop, and once the maximum number of times is reached, the loop automatically terminates. The following example loops through the sequence of 1-100 and.
Copy Code code as follows:
$sum =0
for ($i =1; $i-le; $i + +)
{
$sum + + $i
}
$sum
A For loop is a special type of while loop
In parentheses starting with the For loop, the statement separated by semicolons is the control condition for the loop, respectively: Initialize, loop to execute the conditions that are met, increment.
The first and third of the control statements for the loop can be null:
Copy Code code as follows:
$sum =0
$i =1
for (; $i-le 100;)
{
$sum + + $i
$i + +
}
$sum
Special applications for Loops
The example for loop above stays on the digital level, but what the while loop can do, for loops can be, but sometimes inconvenient. For example, to determine the domain name example:
Copy Code code as follows:
for ($domain = "";! ($domain-like "www.*.*"); $domain =read-host "Input domain")
{
Write-host-foregroundcolor "Green" "please give a valid domain name."
}
Please give a valid domain name.
Input domain:www
Please give a valid domain name.
Input domain:mossfly.com
Please give a valid domain name.
The following example shows reading a text file line by row
Copy Code code as follows:
for ($file =[io. File]::opentext ("C:autoexec.bat");! ($file. Endofstream); $line = $file. ReadLine ())
{
$line;
}
$file. Close ()
REM Dummy file for NTVDM