0

I am trying to retrieve an array and at the end I want to put all of them as a list into an hash, but I get only index and not the list of values.

$testArray = [System.Collections.ArrayList]@()
$tempArray = "123", "321", "453"
foreach($item in $tempArray) {
    if ($item -notlike 123) {
        $arrayID = $testArray.Add($item);
    }
}

@{"mailboxes" = $arrayID};

As a result I would like to see values like

mailboxes {321, 453}

instead of index like below.

mailboxes 1
1
  • @{"mailboxes" = $arrayID} -> @{"mailboxes" = $testArray} Commented Jul 10, 2019 at 13:03

2 Answers 2

2

The ArrayList.Add() method returns the index of the new array element, so you are just adding an integer to $arrayID. Instead:

$testArray = [System.Collections.ArrayList]@()
$tempArray = "123", "321", "453"
foreach($item in $tempArray) {
    if ($item -notlike 123) {
        $testArray.Add($item);
    }
}
@{ "mailboxes" = $testArray};

returns:

mailboxes                      {321, 453}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing to the issue but still i get Output like: 0 1 Name Value ---- ----- mailboxes {321, 453} How to avoid that index part i.e 0 1
@rora Set $null = $testArray.Add($item) or just [void]$testArray.Add($item) to stop index from being returned
This did help me.
0

if you end goal is to get this

mailboxes {321, 453}

then you could do this

$OldArray = @("123", "321", "453")

[System.Collections.ArrayList]$NewArray = @()

foreach($item in $OldArray) {
    if ($item -ne 123) {
        $NewArray += item 
    }
}

@{"mailboxes" = $NewArray};

or just this...

@{"mailboxes" =  @("123", "321", "453") | ? {$_ -ne 123}};

side note: @() by default creates a [system.array] which are fixed in size. using += on a [system.array] will result in a new array being created and the old array contents will need to be copied into it. [System.Collections.ArrayList] are dynamically size, they allow you to easily add new items.

Comments

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.