What objects are suitable for Add-Member?

The documentation reads:

Adds a custom user element to an instance of the Windows PowerShell object.

What does a Windows PowerShell object mean?

This works great:

$obj = new-object system.object $obj | add-member -membertype noteproperty -name Name -value "OK" $obj.name 

But this is not so:

 $obj = @{} 

Actually, I'm trying to add a property to $ error [0].

+6
powershell
source share
1 answer

PowerShell has a so-called PSObject, which is a wrapper around any .NET object (or it can be a fully customizable object), and when you call Add-Member, PowerShell implicitly wraps the real .NET object with PSObject.

The way Add-Member works depends on whether or not it started with PSObject. If you have not started with PSObject, Add-Member will wrap the input in PSObject, and you will need to re-assign the variable to see the adapted object.

So for example:

 $x = [Environment]::OSVersion $x | Add-Member NoteProperty IsVista $true $x | Format-List # does not show the new property 

This is because OSVersion is not wrapped in PSObject. The Add-Member element wraps it, but this wrapper is lost because you are not reinstalling $ x on the wrapped object. Contrast with this behavior:

 $x = New-Object OperatingSystem ('Win32NT', '6.0') $x | Add-Member NoteProperty IsVista $true $x | Format-List # DOES show the new property 

This is because New-Object implicitly wraps a new instance in PSObject. Thus, your Add-Member call adds members to an existing shell.

Returning to the first example, you can make it work properly by changing it to:

 $x = [Environment]::OSVersion $x = $x | Add-Member NoteProperty IsVista $true -PassThru $x | Format-List # DOES show the new property 

Now, after all this, the reason the Hashtable doesn’t work the way you expect is because the Hashtables are handled by special PowerShells, and basically the adapter for the Hashtables uses keys, because the (kinda) and Add-Member properties will not work the way expected with this kind of facility.

+16
source share

All Articles