PowerTip: Change Value of Element in PowerShell Array

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)

Comments (4)

  1. Boe Prox says:

    @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

  2. Will Irwin says:

    Why would you do that versus
    $a[0] = 50

  3. Ken Row says:

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

  4. James Brown says:

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

Skip to main content