PowerShell: How to Check if Object has Specific Property


Often you may want to check if an object has a specific property in PowerShell.

You can use the following methods to do so:

Method 1: Check if Object has Property (Return True or False)

$my_object.PSobject.Properties.Name -contains 'this_property'

This particular example checks if the object named $my_object contains the property named this_property and returns either True or False as a result.

Method 2: Check if Object has Property (Use with if Statement)

if($my_object| Get-Member this_property){
    Write-Host 'Has Property'
}

This particular example checks if the object named $my_object contains the property named this_property and returns ‘Has Property’ if it does contain the property or else it returns nothing.

The following example shows how to use each of these methods in practice.

Example: How to Check if Object has Specific Property in PowerShell

For this example, we will create a variable named $host_info that holds the object produced by the Get-Host cmdlet, which contains information about the program hosting our PowerShell.

We can use the following syntax to create this variable and then view all of its properties:

$host_info = Get-Host
$host_info.psobject.Properties.Name

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

Suppose that we would like to check if a property named UI exists in this object.

We can use the following syntax to do so:

$host_info.PSobject.Properties.Name -contains 'UI' 

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

PowerShell check if object has property

The object does contain the property named UI so it returns True as a result.

We can also use the following syntax to use an if statement to check if the property exists and write custom output instead:’

if($my_object| Get-Member this_property){
    Write-Host 'Has Property'
}

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

PowerShell check if object has property in if statement

The object does contain the property named UI so the if statement returns Has Property as a result.

Related Tutorials

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

PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties
PowerShell: How to Use Where-Object in List

Leave a Reply