I’m trying to use the PowerShell Add-Member cmd on all the items in an array and then access the member I added later but it doesn’t show up.
You can see in the output of the below code that the NoteProperty appears to exist within the scope of the foreach statement but it doesn’t exist on the same object outside of that scope.
Any way to get this script to show isPrime on both calls to Get-Member?
$p = @(1)
$p[0] | %{ add-member -inputobject $_ -membertype noteproperty -name isPrime -value $true; $_ | gm }
$p[0] | gm
output
TypeName: System.Int32
Name MemberType
---- ----------
CompareTo Method
Equals Method
GetHashCode Method
GetType Method
GetTypeCode Method
ToString Method
isPrime NoteProperty
CompareTo Method
Equals Method
GetHashCode Method
GetType Method
GetTypeCode Method
ToString Method
The problem you are running into is that 1, an integer, is a value type in .NET and when it is passed around it is copied (pass by value). So you successfully modified a copy of 1 but not the original one in the array. You can see this if you box (or cast) the 1 to an object (reference type) e.g.:
OP (spoon16) Answer
This is how my code in my script actually ended up looking. If this can be optimized please feel free to edit.