#18 PowerShell Learning: Selecting Parts of Objects

Table of Contents

Selecting parts of objects

You can use the Select-Object cmdlet to create new, custom PowerShell objects that contain properties selected from the objects you use to create them. 

Type the following command to create a new object that includes only the Name and FreeSpace properties of the Win32_LogicalDisk WMI class:

PS C:\> Get-CimInstance -Class Win32_LogicalDisk

DeviceID DriveType ProviderName            VolumeName   Size           FreeSpace
-------- --------- ------------            ----------   ----           ---------
C:       3                                 OS           213970317312   79270346752
D:       3                                 DATA         297359372288   237870116864
P:       2                                 pCloud Drive 2199023255552  1442060361728
Z:       4         \\ExpanDrive\e8psvd7c-1 Amazon S3    10995116277760 10995116277760


PS C:\> Get-CimInstance -Class Win32_LogicalDisk | Select-Object -Property Name, FreeSpace

Name      FreeSpace
----      ---------
C:      79271546880
D:     237870116864
P:    1442060361728
Z:   10995116277760

With Select-Object you can create calculated properties to display FreeSpace in gigabytes rather than bytes.

Get-CimInstance -Class Win32_LogicalDisk |
    Select-Object -Property Name, @{
        label='FreeSpace' ; expression={($_.FreeSpace/1GB).ToString('F2')}
    }
Name FreeSpace
---- ---------
C:   73.83
D:   221.53
P:   1343.02
Z:   10240.00
Get-CimInstance -Class Win32_LogicalDisk |
    Select-Object -Property Name, `
    @{label='FreeSpace' ; expression={($_.FreeSpace/1GB).ToString('F2')}}, `
    @{label='Volume' ; expression={$_.VolumeName}}
Name FreeSpace Volume
---- --------- ------
C:   73.84     OS
D:   221.53    DATA
P:   1343.02   pCloud Drive
Z:   10240.00  Amazon S3
#Learning PowerShell (Articles in series)Cmdlets
#1Getting Started with Windows PowerShell
#2Working with Windows PowerShell
#3Writing and Running PowerShell Scripts
#4Windows PowerShell Remoting
#5Windows PowerShell Profiles
#6PowerShell Drives and Providers
#7Windows PowerShell ISE
#8Manage Services using PowerShell
#9Manage Processes using PowerShellGet-Member, -Property, -ExpandProperty
#10Variables in Windows PowerShell
#11Arrays in Windows PowerShell
#12Hash Tables in Windows PowerShell
#13PowerShell Loopsforeach, for
#14Conditional Logic in PowerShell
#15PowerShell Functions
#16One-liners and the Pipeline
#17Everything about PSCustomObject
#18Selecting Parts of Objects
#19Sorting Objects
#20Getting WMI objects with Get-CimInstance
#21Parentheses, Braces and Square Brackets() {} []
#22The Philosophy Verb-NounGet-Command, Verb-Noun
#23PowerShell Parameters$
#24PowerShell and WMIGet-CimInstance

Leave a Comment

Required fields are marked *