4

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 

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! KTMs and Moab (where that was taken) go together very nicely. :-)
2

I would optimize, by typing less:

$p | add-member noteproperty isPrime $true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.