02 / WORKING WITH DATA · LESSON 07

Find what needs attention

Use Where-Object and Select-Object to answer a focused question.

10 min · learn at your pace

Filter records

Where-Object keeps objects that match a condition. Inside its script block, $_ means the current object:

$devices | Where-Object { $_.Status -eq 'Offline' }

-eq compares two values for equality. Each device is considered in turn; only matches continue down the pipeline.

For simple comparisons, PowerShell also offers a shorter form:

$devices | Where-Object Status -eq 'Offline'

Choose properties

Select-Object chooses which properties the next stage receives:

$devices | Select-Object Name, Status

You can combine these steps to produce a focused report. Filtering changes which records you keep. Selecting changes the properties on each retained record.

Use Select-Object -ExpandProperty Name when you want just the property values, such as a stream of device names. That is different from objects which each have a Name property.

Try an example.ps1
$devices = @(
    [pscustomobject]@{Name='WEB-01'; Status='Online'; Team='Apps'}
    [pscustomobject]@{Name='DB-01'; Status='Offline'; Team='Data'}
    [pscustomobject]@{Name='WEB-02'; Status='Offline'; Team='Apps'}
)
$devices | Where-Object Status -eq 'Offline'
YOUR TURN

Put it into practice.

Return the offline devices as objects containing only the Name property. The result should contain DB-01 and WEB-02.

See an explained solution
One way to solve it.ps1
$devices = @(
    [pscustomobject]@{Name='WEB-01'; Status='Online'; Team='Apps'}
    [pscustomobject]@{Name='DB-01'; Status='Offline'; Team='Data'}
    [pscustomobject]@{Name='WEB-02'; Status='Offline'; Team='Apps'}
)
$devices | Where-Object { $_.Status -eq 'Offline' } | Select-Object Name

Where-Object keeps the two offline devices. Select-Object creates a focused one-property record for each result.