1

I have a string of data which I turn into an array thus:

$cfg_data = @(
"AppName1,data1",
"AppName2,data2"    
) 

I then run a foreach query to work on each line at a time:

FOREACH($a in $cfg_data)
{
    $dataSplit = $a -split"(,)"
    $AppN = $dataSplit[0]
    $AppD = $dataSplit[2]

    #Do stuff here
}

But I want to convert this from a string to an Object, so I can add/remove additional items, and then run some more foreach statements, updating the different bits as I go.

I have got as far as:

FOREACH($a in $cfg_data)
{
    $dataSplit = $a -split"(,)"
    $AppN = $dataSplit[0]
    $AppD = $dataSplit[2]

        $objHere = @(
            @{ 
                appItem = "$AppN";
                appData = "$AppD";
             }) 
}

But when I check $objHere it just has the last entry in it (AppName2, datat2)

I tried adding:

$b=0

and

$objHere[$b]

but then I get

Array assignment failed because index '1' was out of range.

What is the correct way to do this?

1
  • 1
    Thats because you overwrite the object every time you loop, add it to an object array inside your loop and you should be fine (syntax: $arr+=$objhere) Commented Nov 28, 2014 at 12:07

1 Answer 1

3

By declaring $objHere in the loop, you overwrite the value on each iteration. You need to initialise an empty array outside the loop and append to it from within the loop:

$objHere = @()

foreach($a in $cfg_data)
{
    $dataSplit = $a -split"(,)"
    $AppN = $dataSplit[0]
    $AppD = $dataSplit[2]

    $objHere += 
        @{ 
           appItem = "$AppN";
           appData = "$AppD";
         }
}

In addition, you're not actually creating an object, you're creating a hashtable. If you wanted to create an object instead, you could do this:

$objHere = @()

foreach($a in $cfg_data)
{
    $dataSplit = $a -split"(,)"
    $AppN = $dataSplit[0]
    $AppD = $dataSplit[2]
    $objHere += New-Object PSObject -property @{appItem = "$AppN";appData = "$AppD";}
}

Giving:

appItem  appData
-------  -------
AppName1 data1
AppName2 data2
Sign up to request clarification or add additional context in comments.

1 Comment

you are a star. It seems so obvious once someone points out the mistakes. Cheers

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.