当前位置: 移动技术网 > IT编程>脚本编程>Shell > 探索PowerShell(十) 循环语句介绍

探索PowerShell(十) 循环语句介绍

2017年12月12日  | 移动技术网IT编程  | 我要评论
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"}

运行结果:



欢迎提出意见建议!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网