PowerShell作为可编程性语言,拥有以下循环语句。
注:本节所要讨论的内容的实质更多的偏向于程序设计方面,所以在此不做过多详细讲解,只针对PowerShell中的应用进行具体讲解。
• for (初值;表达式;赋值语句) {代码} 用变量值控制执行次数
• foreach (成员变量 in 数组) {代码} 利用迭代执行代码
• foreach-object 对一组输入的每个对象执行运算
• while(表达式) {代码} 表达式为真时循环执行代码
• do {代码} while(表达式) 类似于while,只是先执行代码,再判断表达式真假
• do {代码} until(表达式) 执行代码,直至表达式为假
循环语句在PowerShell中的应用
利用foreach查询硬件信息
例一:
- $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
- }
运行结果:
例二:
- $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
- }
运行结果:
使用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")
运行结果:
使用foreach-object进行格式化输出
对下列数据进行操作,
D00454798106276487326471李德建829.51 Q00136284503715856294375张春生712.65 H00374967692981018226574刘锡明891.31 R00759861215965098103878赵子龙898.21 J00741245626115645970139杨高远-13.21 K00142545764587219409172周明647.41 P00103851828756182786938张龙-27.51 |
使之输出为以下所示格式:
1|454798106276487326471|李德建|829.51 2|136284503715856294375|张春生|712.65 3|374967692981018226574|刘锡明|891.31 4|759861215965098103878|赵子龙|898.21 5|741245626115645970139|杨高远|0.00 6|142545764587219409172|周明|647.41 7|103851828756182786938|张龙|0.00 小计 |3979.09 |
使用foreach-object对每个数据成员使用正则表达式,最后格式化输出即可:
- ${C:\test.txt} | `
- foreach-object{$total=0;$id=1}`
- {
- [void]($_ -match '^.{3}(?<id>\d+)(?<name>[\p{IsCJKUnifiedIdeographs}]+)(?<salary>[\d.]*)');
- $ofs = '|';
- "$($id;$id++;$matches.id;$matches.name;'{0:f2}' -f [float]$matches.salary)";
- $total += $matches.salary
- }`
- {"`t小计`t`t|$total"}
运行结果:
欢迎提出意见建议!