PowerShell: How to Use Where-Object is Not Null


Often you may want to use the Where-Object cmdlet in PowerShell to filter an object to only contain items where a specific property or field is not null.

You can use the following basic syntax to do so:

Import-Csv nba_data.csv | Where-Object { $_.assists}

This particular example will import the CSV file named nba_data.csv and filter the file to only display rows where the value in the assists column is not null.

Note that by specifying $_.assists inside the Where-Object cmdlet we are able to specify that we want to filter for rows where a value simply exists in the assists column.

This is equivalent to filtering for rows where the value in the assists column is not null.

The following example shows how to use this syntax in practice.

Example: How to Use Where-Object is Not Null in PowerShell

Suppose we have a CSV file named nba_data.csv that contains information about various basketball players.

We can use the Import-Csv cmdlet to view the contents of this entire file:

The file contains three columns that show the team, points and assists for various basketball players.

Notice that several values in the assists column are missing.

We can use the following syntax with the Where-Object cmdlet to filter the rows of this CSV file to only display the rows where the value in the assists column are not null:

Import-Csv nba_data.csv | Where-Object { $_.assists}

The following screenshot shows how to use this syntax in practice:

PowerShell Where-Object not null

Notice that this returns only the rows from the CSV file where the value in the assists column is not null.

To filter for rows where the value is not null in another column, simply replace assists with the name of another column.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Where-Object in List
PowerShell: How to Use Where-Object with Multiple Conditions
PowerShell: How to Use -notlike With Multiple Values

Leave a Reply