Windows Vista Forums

how to assign values to array and how to create array via variable
  1. #1


    Frank Guest

    how to assign values to array and how to create array via variable

    Hi,

    I need to assign values to an array, but they may not be in order. ie,

    $ar[0] = "test"
    but I get the error:



    Array assignment failed because index '0' was out of range.
    At line:1 char:5
    + $ar[0 <<<< ] = "test"

    I can add them in sequence, via: $ar += "test" but I cannot add via specific
    element.

    Also, is there a way to create an array via a variable name, ie:

    $var1 = "testname"

    $(`$var1`) = @()

    The goal is to create an array $testname.

    Thanks in advance,

    Frank



      My System SpecsSystem Spec

  2. #2


    Clint Bergman Guest

    Re: how to assign values to array and how to create array via variable

    You can create an array like this:
    $varArray = "Value1","Value2","Value3","Value4","Value5"

    and append values as you noted:
    $varArray += "Value6"

    I don't think you can just randomly assign a value to an arbitrary element.
    Changing an arbitrary element is easy though. So what I have done in the
    past is something like this:

    # Create the array with however many elements I think I might need:
    $Arr = 1..20
    # Now I can modify any of the elements (0-19, not 1-20)
    $Arr[2] = "Value1"
    $Arr[6] = "Value6"
    # And append more elements in chunks if I need
    $Arr += 1..10

    for more info:
    get-help about_array

    ~Clint

    "Frank" <Frank@discussions.microsoft.com> wrote in message
    news:104CD347-3D9A-4546-BC64-4A41E9702912@microsoft.com...
    > Hi,
    >
    > I need to assign values to an array, but they may not be in order. ie,
    >
    > $ar[0] = "test"
    > but I get the error:
    >
    > Array assignment failed because index '0' was out of range.
    > At line:1 char:5
    > + $ar[0 <<<< ] = "test"
    >
    > I can add them in sequence, via: $ar += "test" but I cannot add via
    > specific
    > element.
    >
    > Also, is there a way to create an array via a variable name, ie:
    >
    > $var1 = "testname"
    >
    > $(`$var1`) = @()
    >
    > The goal is to create an array $testname.
    >
    > Thanks in advance,
    >
    > Frank
    >
    >




      My System SpecsSystem Spec

how to assign values to array and how to create array via variable problems?

Similar Threads
Thread Thread Starter Forum Replies Last Post
How to create array without quotes? $array = (a,b,c) BenConrad PowerShell 5 04 Feb 2009
How do i retrieve only the values from array ? IT Staff PowerShell 1 24 Oct 2008
Read-Host values into an Array Flea# PowerShell 5 05 Sep 2008
Getting all values out of an array of objects casey.daniell PowerShell 6 22 Feb 2008
Initialize array without values Frank PowerShell 11 02 Mar 2007