Windows Powershell For 循環(huán)
如果你知道循環(huán)的確切次數(shù)可以使用For循環(huán),F(xiàn)or循環(huán)屬于計數(shù)型循環(huán),一旦達到最大次數(shù),循環(huán)就會自動終止。下面的例子通過循環(huán)求1-100的數(shù)列和。
$sum=0
for($i=1;$i -le 100;$i++)
{
$sum+=$i
}
$sum
For循環(huán)是特殊類型的While循環(huán)
在For循環(huán)開始的圓括號中,由分號隔開的語句為循環(huán)的控制條件,分別為:初始化,循環(huán)執(zhí)行滿足的條件,增量。
For循環(huán)的控制語句第一個和第三個可以為空:
$sum=0
$i=1
for(;$i -le 100;)
{
$sum+=$i
$i++
}
$sum
For循環(huán)的特殊應用
上面的For循環(huán)示例停留在數(shù)字層面上,其實While循環(huán)能辦到的事,F(xiàn)or循環(huán)也可以,只是可能有時不方便而已。例如判斷域名的例子:
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.
下面的例子演示逐行讀取文本文件
for($file=[IO.File]::OpenText("c:autoexec.bat") ; !($file.EndOfStream);$line=$file.ReadLine() )
{
$line;
}
$file.Close()
REM Dummy file for NTVDM
相關文章
Windows Powershell 命令返回數(shù)組
這篇文章主要介紹了Windows Powershell 命令返回數(shù)組的使用方法,需要的朋友可以參考下2014-09-09