Element to add PowerShell to array elements

I am trying to use cmd for PowerShell Add-Member for all elements of an array, and then access the member that I added later, but it does not appear.

In the output of the code below, you can see that NoteProperty exists within the scope of the foreach statement, but it does not exist on the same object outside this scope.

How to get this script to display isPrime for both Get-Member calls?

 $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
source share
2 answers

The problem you are facing is that 1, an integer, is a value type in .NET and when it is passed, it is copied (passed by value). Thus, you have successfully modified copy 1, but not the original one in the array. You can see this if you put (or discard) 1 into an object (link type), for example:

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

OP (spoon16) Answer

So my code in my script actually ended. If this can be optimized, feel free to edit.

 $p = @() #declare array 2..$n | %{ $p += [psobject] $_ } #initialize $p | add-member -membertype noteproperty -name isPrime -value $true 
+5
source

I would optimize by typing less:

 $p | add-member noteproperty isPrime $true 
+2
source

All Articles