Windows PowerShell Filter Pipe Results _powershell

Source: Internet
Author: User

You can use Where-object if you want to filter objects, and if you want to filter the properties of objects, you can use Select-object, or you can use Foreach-object if you want to customize the personalized filtering effect. Finally, if you want to filter for duplicate results, use Get-uinque.

Filter objects in a pipe result

If you are interested only in the specific object of the pipe result, use Where-object to filter each result strictly, and if you meet your criteria, it will be retained and discarded automatically if the criteria are not met. For example, you can view the current service running on the machine through Get-service, but you may only care about which services are running, and then filter by the property status of each service. But the prerequisite is that you have to know in advance what attributes are available to the object in question. 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 Ca
Nstop:true displayname:adobe Acrobat Update Service dependentservices: {} machinename:. Servicename:adobearmservice Servicesdependedon: {} ServiceHandle:Status:Running servicetype:win3 2OwnProcess 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 ...

Knowing what attributes the object has, it is 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

Here's a little explanation, Where-object's argument is a Boolean expression that $_ represents the current result of the pipeline during the filtering process. In addition, Where-object also 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 attributes you are interested in, you can use Select-object to restrict the properties of the object. The next example shows the complete information on the 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 5 files that were last modified

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

  directory: 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 largest CPU

PS c:powershell> get-process | Sort-descending CPU | Select-first 5 Handles NPM (k) PM (k) (k)

VM (M) CPU (s)  Id processname
------------------------------- ---  -------------
  1336   844304 809388 1081 164.69 3060 iexplore
  224   Ten 74676 62468  188 81.10 4460 AcroRd32
  130 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 pipe results individually

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

ls | foreach-object {"FileName: 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, each traversal will be compared with the previous object, if the same as the previous object will discard the current object, otherwise the reservation. So if there is no sort in the object list, Get-unique does not fully function, only to ensure that adjacent objects do not repeat.

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

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.