次の方法で共有


Using the Select-Object Cmdlet

Selecting Specific Properties of an Object

One of the more useful capabilities of the Select-Object cmdlet is the ability to grab a selected number of objects from the beginning (or the end) of a sorted collection. For example, suppose you use the Get-ChildItem cmdlet to get a list of all the files in the C:\Windows folder; you then pipe that information to the Sort-Object cmdlet and sort the files by size (length). Now suppose all you really care about are the three largest files in the folder; how do you go about determining that?

Here’s how:

Get-ChildItem c:\windows\*.* | Sort-Object length -descending | Select-Object -first 3

After you’ve sorted the collection in descending order, the largest file will be at the top and the smallest file will be at the bottom. To determine the three largest files in the collection simply call Select-Object and include the -first parameter, specifying the number of items to return. In other words:

Select-Object -first 3

What if you wanted the three smallest files? Well, seeing as how those three files will be at the bottom of the list, you simply use the -last parameter, like so:

Get-ChildItem c:\windows\*.* | Sort-Object length -descending | Select-Object -last 3

You can also use Select-Object to specify that only selected properties from an object should be used in your command (e.g., only certain properties should be shown on-screen). For example, by default any time you run the Get-Process cmdlet and pipe it through Format-List, you get back something that looks like this:

Id      : 1924
Handles : 273
CPU     : 2.046875
Name    : svchost

But suppose all you really wanted was to see the process Name and ID? That’s fine: just pass the process information through Select-Object, and ask it to pick out only the Name and ID properties:

Get-Process | Select-Object name,id | Format-List

What will that give you? That will give you output that looks like this:

Name : atiptaxx
Id   : 2440

Name : BTStackServer
Id   : 524

To ensure that you retrieve all the properties and property values, use the wildcard character. This command retrieves process information and then displays all the properties as a list:

Get-Process | Select-Object *

Good question: suppose you did want all the properties except for Site and Container. No problem; just tack on the -exclude parameter and indicate the properties that should be excluded from the returned dataset:

Get-Process | Select-Object * -exclude site,container
Select-Object Aliases
  • select