标签:powershell 循环语句
PowerShell 循环语句
介绍
for (初值;表达式;赋值语句) {代码} 用变量值控制执行次数
foreach (成员变量 in数组) {代码} 利用迭代执行代码
foreach-object 对一组输入的每个对象执行运算
while(表达式) {代码} 表达式为真时循环执行代码
do {代码} while(表达式) 类似于while, 只是先执行代码,再判断表达式真假
do {代码} until(表达式) 执行代码, 直至表达式为假
2. 实际应用
例一:使用foreach 查询硬件信息(disk)
$DiskDrive=get-wmiobject-class Win32_DiskDrive -namespace root\CIMV2
foreach($item in $DiskDrive)
{
write-host"Description:" $item.Description
write-host"Device ID:" $item.DeviceID
write-host"Interface Type:" $item.InterfaceType
write-host"Media Type:" $item.MediaType
write-host"Model:" $item.Model
write-host"Partitions:" $item.Partitions
write-host"Size:" $item.Size
write-host"Status:" $item.Status
}
结果1:
Description: Disk drive
Device ID: \\.\PHYSICALDRIVE0
Interface Type: IDE
Media Type: Fixed hard disk media
Model: ST3320413AS
Partitions: 1
Size: 320070320640
Status: OK
Description: Disk drive
Device ID: \\.\PHYSICALDRIVE1
Interface Type: IDE
Media Type: Fixed hard disk media
Model: ST3320413AS
Partitions: 3
Size: 320070320640
Status: OK
例二:使用foreach 查询硬件信息(CPU)
$Processor=get-wmiobject-class Win32_Processor -namespace root\CIMV2
foreach($item in $Processor)
{
write-host"Caption:" $item.Caption
write-host"CPU Status:" $item.CpuStatus
write-host"Current Clock Speed:" $item.CurrentClockSpeed
write-host"Device ID:" $item.DeviceID
write-host"L2 Cache Size:" $item.L2CacheSize
write-host"L2 Cache Speed:" $item.L2CacheSpeed
write-host"Name:" $item.Name
}
结果2:
Caption: Intel64 Family 6 Model 42 Stepping7
CPU Status: 1
Current Clock Speed: 3101
Device ID: CPU0
L2 Cache Size: 1024
L2 Cache Speed:
Name: Intel(R) Core(TM) i5-2400 CPU @3.10GHz
例三:使用while;do…while监视进程状态
Notepad
While(get-process-name notepad | select -Property Responding){}
$time =get-date
Write-Host"The Notepad failed to respond on:$time"
在此例下,若进程notepad出现未响应,则会产生屏幕输出。
使用do while表达:
notepad
do{}
While(get-process-name notepad | select -Property Responding)
$time =get-date
Write-Host"The Notepad failed to respond on:$time"
例四:利用do until进行交互
do
{
"Quit Now? (Y/N)"
$input=Read-Host
}
until($input-eq "Y")
运行结果:
PSC:\> do
>>{
>> "Quit Now? (Y/N)"
>> $input=Read-Host
>>}
>>until($input -eq "Y")
>>
QuitNow? (Y/N)
y
PSC:\>
参考:http://marui.blog.51cto.com/1034148/294113
本文出自 “Ricky's Blog” 博客,请务必保留此出处http://57388.blog.51cto.com/47388/1639266
标签:powershell 循环语句
原文地址:http://57388.blog.51cto.com/47388/1639266