PowerShell Filter Pipeline Results

Source: Internet
Author: User

The ability to filter the properties of certain objects and objects through a pipeline is useful because many times we are not interested in all the results and may only be interested in some of the results. You can use Where-object if you want to filter objects, or you can use Select-object if you want to filter the properties of an object, or you can use Foreach-object if you want to customize a personalized filter effect. Finally, if you want to filter the duplicate results, use Get-uinque.

Filter objects in pipeline results

If you are only interested in the specific objects of the pipeline results, use Where-object to carefully filter each result, and once your criteria are met, it will be discarded automatically if the criteria are not met. For example, you can view the current service running on the machine through Get-service, but may only care about which services are running, and then filter through the properties status of each service. But the precondition is that you know in advance what properties the object is to be processed. You can pass Format-list *, or you can pass get-memeber.

PS c:powershell> Get-service | Select-object-first 1 | Format-list *

Name:adobearmservice
Requiredservices: {}
Canpauseandcontinue:false
Canshutdown:false
Canstop:true
Displayname:adobe Acrobat Update Service
Dependentservices: {}
MachineName:.
Servicename:adobearmservice
Servicesdependedon: {}
Servicehandle:
Status:running
Servicetype:win32ownprocess
Site:
Container:

PS c:powershell> Get-service | Select-object-first 1 | Get-member-membertype
Property

TypeName:System.ServiceProcess.ServiceController

Name membertype Definition
------------------------
CanPauseAndContinue Property System.Boolean canpauseandcontinue {get;}
CanShutdown Property System.Boolean canshutdown {get;}
CanStop Property System.Boolean CanStop {get;}
Container Property System.ComponentModel.IContainer Container {g ...
Dependentservices Property system.serviceprocess.servicecontroller[] Dep ...
DisplayName Property System.String DisplayName {get;set;}
MachineName Property System.String machinename {Get;set;}
Servicehandle Property System.Runtime.InteropServices.SafeHandle Ser ...
ServiceName Property System.String ServiceName {get;set;}
Servicesdependedon Property system.serviceprocess.servicecontroller[] Ser ...
ServiceType Property System.ServiceProcess.ServiceType servicetype ...
Site Property System.ComponentModel.ISite site {get;set;}
Status Property System.ServiceProcess.ServiceControllerStatus ... The
knows what properties the object has, and it's easy to complete the requirements mentioned above.

PS c:powershell> Get-service | Where-object {$_. Status-eq "Running"}

Status Name DisplayName
------ ---- -----------
Running adobearmservice Adobe Acrobat Update Service
Running apphostsvc application Host Helper Service
Running appidsvc Application Identity
Running Appinfo Application Information
Running AUDIOENDPOINTBU ... Windows Audio Endpoint Builder
Running audiosrv Windows Audio
Running bdesvc BitLocker Drive Encryption Service
Running BFE Base Filtering Engine
Running BITS Background Intelligent Transfer Ser ...
Running CcmExec SMS Agent Host
A little explanation here is that the Where-object parameter is a Boolean expression that $_ represents the current result of the pipeline passing through the filter. In addition Where-object has an alias "?" more image.

Select an object's properties

There may be a lot of properties contained in each object, but not all of the properties you are interested in, you can use Select-object to restrict the properties of the object. The following example shows if you get the complete information for an anonymous account on the machine.

PS c:usersv-bali.fareast> get-wmiobject win32_useraccount-filter "Localaccount=true and Name= ' guest '"

accounttype:512
Caption:myhomeguest
Domain:myhome
sid:s-1-5-21-3064017030-3269374297-2491181182-501
FullName:
Name:guest
If you are interested only in user name, description, enable.

PS c:powershell> get-wmiobject win32_useraccount-filter "Localaccount=true and
Name= ' Guest ' | Select-object name,description,disabled

Name Description Disabled
---- ----------- --------
Guest built-in account for Gu ... True
Select-object also supports wildcard characters.

Dir | Select-object *-exclude *a*
Limit the number of objects

List the last 5 files modified

PS c:powershell> Dir | Select-object-excludeproperty "*n*"-first 5

Catalog: C:powershell

Mode LastWriteTime Length Name
---- ------------- ------ ----
-A---2011/11/24 18:30 67580 a.html
-A---2011/11/24 20:04 26384 a.txt
-A---2011/11/24 20:26 12060 alias
-A---2011/11/25 11:20 556 employee.xml
-A---2011/11/29 19:23 21466 function.ps1
List 5 processes that consume the most CPU

PS c:powershell> get-process | Sort-descending CPU | Select-first 5

Handles NPM (k) PM (k) WS (k) VM (M) CPU (s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
1336 98 844304 809388 1081 164.69 3060 iexplore
224 74676 62468 188 81.10 4460 ACRORD32
9 28264 39092 167 70.57 3436 DWM
169 8 7576 29568 134 65.22 3364 Notepad
989 72484 35996 393 62.67 4724 bingdict
Process all pipeline results individually

If you want to personalize the pipeline results individually, use Foreach-object

ls | Foreach-object {"File name: File Size (M):"-f $_. Name,$_. LENGTH/1M}
PS c:powershell> ls | foreach-object {"FileName: {0} File size {1}kb:"-f $_. Name,
($_.length/1kb). ToString ()}
File name: a.html File size 65.99609375KB:
File name: a.txt File size 25.765625KB:
File name: Alias file size 11.77734375KB:
File name: Employee.xml File size 0.54296875KB:
File name: Function.ps1 File size 20.962890625KB:
File name: Logotestconfig.xml File size 0.181640625KB:
File name: ls.html File size 3.37890625KB:
Delete Duplicate objects

Get-unique can remove duplicate objects from the sorted list of objects. Get-unique will iterate through the object one at a time, comparing it to the previous object on each traversal, and if it is equal to the previous object it discards the current object, otherwise it remains. So if there is no sort in the list of objects, Get-unique does not work completely, only to ensure that the adjacent objects are not duplicated.

PS c:powershell> 1,2,1,2 | Get-unique
1
2
1
2
PS c:powershell> 1,2,1,2 | Sort-object | Get-unique
1
2
PS c:powershell> ls | Foreach{$_.extension} | Sort-object | Get-unique

. bat
. html
. PS1
. txt
. vbs
. xml
This article link: http://www.pstips.net/powershell-filtering-pipeline-result

PowerShell Filter Pipeline Results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.