PowerTip: Change Value of Element in PowerShell Array

PowerTip: Change Value of Element in PowerShell Array

  • Comments 4
  • Likes

Summary: Learn how to change the value of an element in a Windows PowerShell array.

Hey, Scripting Guy! Question How can I use Windows PowerShell to change the value of the first element in an array?

Hey, Scripting Guy! Answer Use the Set method and specify the element number and the new value, for example:

PS C:\> $a = 1,2,3,4,5

PS C:\> $a.Set(0,50)

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Why would you do that versus
    $a[0] = 50
    ?

  • Yes, inquiring minds want to know. Maybe the .set() method is more useful in certain contexts?

  • I'm curious why piping $a into Get-Member doesn't reveal any Set() method.

  • @James Brown
    When you are piping the contents of the array $a into Get-Member, it is unrolling the items in the collection to process one at a time, which is why those items have the type of System.Int32. In order to see the type information that includes the Set() method on the array, you need to do the following:

    Get-Member -Input $a