Windows Powershell ForEach-Object 循环
对管道对象逐个处理
如果使用get-wmiobject 获取系统中的服务,为了排版可能会也会使用format-table对结果进行表格排版。
ps c:powershell> get-wmiobject win32_service | format-table status,displayname
-autosize
status displayname
------ -----------
ok adobe acrobat update service
ok application experience
ok application layer gateway service
ok application host helper service
ok application identity
ok application information
ok application management
ok asp.net state service
但是如果想对每个服务进行更定制化的处理可是使用foreach-object
ps c:powershell> get-wmiobject win32_service | foreach-object {"name:"+ $_.disp
layname, ", is processid more than 100:" + ($_.processid -gt 100)}
name:adobe acrobat update service , is processid more than 100:true
name:application experience , is processid more than 100:false
name:application layer gateway service , is processid more than 100:false
name:application host helper service , is processid more than 100:true
name:application identity , is processid more than 100:true
name:application information , is processid more than 100:true
name:application management , is processid more than 100:false
name:asp.net state service , is processid more than 100:false
结合条件处理
foreach-object的处理可以包含任意powershell脚本,当然也包括条件语句
get-wmiobject win32_service | foreach-object {
if ($_.processid -gt 3000)
{ "{0}({1})" -f $_.displayname,$_.processid}
}
windows presentation foundation font cache 3.0.0.0(5408)
microsoft network inspection(5260)
branchcache(4112)
windows modules installer(7656)
调用方法
在foreach-object中,$_代表当前对象,当然也允许通过$_,调用该对象支持的方法。
下面的例子杀死所有ie浏览器进程:
ps c:powershell> get-process iexplore
handles npm(k) pm(k) ws(k) vm(m) cpu(s) id processname
------- ------ ----- ----- ----- ------ -- -----------
883 29 14728 22432 181 34.26 4300 iexplore
771 28 55552 129152 425 8.56 5732 iexplore
1216 51 104324 143916 539 572.41 5912 iexplore
801 25 49200 25372 285 5.99 6252 iexplore
691 25 57564 95796 333 8.08 6388 iexplore
1256 38 85848 127012 379 20.37 7856 iexplore
ps c:powershell> get-process iexplore | foreach-object {$_.kill()}
ps c:powershell> get-process iexplore
get-process : 找不到名为“iexplore”的进程。请验证该进程名称,然后再次调用 cmdlet。
所在位置 行:1 字符: 12
+ get-process <<<< iexplore
+ categoryinfo : objectnotfound: (iexplore:string) [get-process],
processcommandexception
+ fullyqualifiederrorid : noprocessfoundforgivenname,microsoft.powershell.
commands.getprocesscommand
下一篇: Python进行区间取值案例讲解
推荐阅读
-
Windows10如何使用PowerShell让局域网电脑集体重启?
-
Windows Server 2016-Powershell之客户端加域
-
Powershell使用WINDOWS事件日志记录程序日志
-
Windows10文件目录下添加 Shift+右键打开管理员Powershell窗口
-
python通过ssh-powershell监控windows的方法
-
PowerShell中查看当前版本、Windows版本、.NET版本信息的代码
-
PowerShell脚本中控制Windows DNS服务的方法
-
windows powershell基础
-
Windows Powershell 介绍和安装
-
Windows Powershell 命令集 cmdlets