Windows Powershell ForEach-Object 循环
对管道对象逐个处理
如果使用Get-WmiObject 获取系统中的服务,为了排版可能会也会使用Format-Table对结果进行表格排版。
PS C:Powershell> Get-WmiObject Win32_Service | Format-Table status,DisplayName -AutoSizestatus 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 iexploreHandles 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
Windows Powershell Foreach 循环
下面举两个例子:$array=7..10foreach($nin$array){$n*$n}#49#64#81#100foreach($fileindirc:windows){if($file.Length-gt1mb){$File.Name}}#explorer.exe#WindowsUpdate.log这里只为了演示foreach
Windows Powershell Do While 循环
继续与终止循环的条件do-while()会先执行再去判断,能保证循环至少执行一次。PSC:Powershelldo{$n=Read-Host}while($n-ne0)10100992012世界末日为什么不退出因为条件
Powershell小技巧之获取MAC地址
在Powershell中获取MAC地址不是很难。这里就有一种方法:PSgetmac/FOCSV|ConvertFrom-CsvPhysicalAddressTransportName------------------------------5C-51-4F-62-F2-7DDeviceTcpip_{FF034A8
标签:条件,进程,对象,方法,例子