Categories

Select is a filter

This is a common scenario:

Get-WmiObject -Class Win32_Logicaldisk | select Name, Size, Freespace

You will see a display with three properties – turning them into a list for ease of display:

Name      : C:
Size      : 248951861248
Freespace : 171627724800

What this means is that you’ve got an object with 3 properties.

£> Get-WmiObject -Class Win32_Logicaldisk | select Name, Size, Freespace | Get-Member


   TypeName: Selected.System.Management.ManagementObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Freespace   NoteProperty System.UInt64 Freespace=171627569152
Name        NoteProperty System.String Name=C:
Size        NoteProperty System.UInt64 Size=248951861248

The object type changes – its now a Selected.System.Management.ManagementObject rather than System.Management.ManagementObject#root\cimv2\Win32_LogicalDisk you get from WMI.

Try this to see the whole list of properties

Get-WmiObject -Class Win32_Logicaldisk | Get-Member

Select-Object is great because you can trim down the size of the objects on your pipeline but you have to remember that once you performed that selection its a one way street you can’t get back to the original.

If you need to perform multiple actions on the objects put them into a variable:

$disks = Get-WmiObject -Class Win32_Logicaldisk

then you can do:

$disks | <pipeline 1>

$disks | <pipeline 2>

or

foreach ($disk in $disks) { <do stuff to the disks>}

Where and when to filter you data using Where-Object or Select-Object is part of your design process and only you know what works in your situation. The rule of thumb is filter early to reduce the data on the pipeline but knowing when to break that rule is what makes or breaks your solution

Leave a Reply