How to Remove Property from PSCustomObject in PowerShell

Problem

In PowerShell, PSCustomObject allows us to create an object on the fly without having to create a class and its members such as Properties, Methods, etc.

This capability makes PSCustomObject an ideal solution for some purposes like combining data into one object and dynamically change the property and behavior of an object.

In this blog post, we will show you several ways to remove property from PSCustomObject in PowerShell.

Using Remove method

In this approach, we access the psobject property of the $fullName object which provides access to the underlying object properties. We then use the Properties.Remove() method to remove MiddleName property from the object. Finally, we display the modified objects to see the changes.


# Create a PSCustomObject
$fullName = [PSCustomObject]@{
    FirstName  = "John"
    MiddleName = "Quincy"
    LastName   = "Adam"
}

# Remove property from object using the Remove() method
$fullName.psobject.Properties.Remove("MiddleName")

# Display modified object
$fullName

The result will look as follows:

Result of Using Remove method

Using Select-Object’s ExcludeProperty Parameter

In this approach, we use the Select-Object cmdlet with the -ExcludeProperty parameter to remove the desired property.

In this example, we exclude MiddleName property from $fullName object using Select-Object -ExcludeProperty MiddleName statement. The modified object is then assigned back to the $fullName variable.


# Create a PSCustomObject
$fullName = [PSCustomObject]@{
    FirstName  = "John"
    MiddleName = "Quincy"
    LastName   = "Adam"
}

# Remove property from the object using ExcludeProperty parameter of Select-Object
$fullName = $fullName | Select-Object -ExcludeProperty MiddleName

# Display modified object
$fullName

The result will look as follows:

Result of Using Select-Object

Conclusion

To remove property from PSCustomObject, we can use Remove method from psobject which is an intrinsic member of PSCustomObject. We can also use the combination of Select-Object and ExcludeProperty parameter to modify the object so that it will exclude the desired property.