PowerShell Remove-Member
The PowerShell Remove-Member cmdlet is used to remove a member (property or method) from an object. It allows you to modify objects on the fly or remove unnecessary members from object instances. The Remove-Member cmdlet helps simplify object manipulation and customization in PowerShell.
Syntax:
Remove-Member [-InputObject] <PSObject> [-MemberType] <MemberTypes> [-Name] <String[]> [-Force] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>]
Parameters:
- -InputObject <PSObject> (Required): Specifies the object from which the member should be removed.
- -MemberType <MemberTypes> (Required): Specifies the type of member to remove, which can be Property, NoteProperty, AliasProperty, ScriptProperty, CodeMethod, MemberSet, PropertySet, or Methods.
- -Name <String[]> (Required): Specifies the names of the members to remove.
- -Force (Optional): Allows the removal of a member that is locked or cannot be removed.
- -PassThru (Optional): Returns an object representing the input object after removing the specified members.
- -WhatIf (Optional): Shows what would happen if the command runs without actually performing any action.
- -Confirm (Optional): Prompts you for confirmation before executing the command.
- <CommonParameters>: This cmdlet supports common parameters.
Example 1: Removing a property from an object
$person = [PSCustomObject]@{ Name = "John" Age = 30 Address = "123 Main St" } $person | Remove-Member -MemberType Property -Name Address $person
Output:
Name Age ---- --- John 30
In this example, we created a custom object called $person with three properties: Name, Age, and Address. Using the Remove-Member cmdlet, we removed the Address property from the $person object. The output shows that the Address property has been successfully removed.
Example 2: Removing a method from an object
$math = [PSCustomObject]@{ Add = { param($a, $b) return $a + $b } Subtract = { param($a, $b) return $a - $b } } $math | Remove-Member -MemberType Methods -Name Subtract $math.Add(5, 3)
Output:
8
In this example, we created a custom object called $math with two methods: Add and Subtract. We used the Remove-Member cmdlet to remove the Subtract method. Finally, we called the Add method, which successfully performed the addition operation, while the Subtract method is no longer available.