views:

813

answers:

2

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
+4  A: 

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.:

$p = @([psobject]1)
$p[0] | %{ add-member NoteProperty isPrime $true; $_ | gm }
$p[0] | gm

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.

$p = @() #declare array
2..$n | %{ $p += [psobject] $_ } #initialize
$p | add-member -membertype noteproperty -name isPrime -value $true
Keith Hill
good answer and nice KTM
spoon16
Thanks! KTMs and Moab (where that was taken) go together very nicely. :-)
Keith Hill
+2  A: 

I would optimize, by typing less:

$p | add-member noteproperty isPrime $true
Doug Finke
thanks !
spoon16