Powershell - Add to array

Hey

$example = ("AAA", "BBB", "CCC")

function calc {
    param ()
   
    return "test1"
    }


$example | % { calc }

How do I add the value from calc to the array? (ext. the array - not just string concatenate)

AAA TEST1
BBB TEST1
CCC TEST1

Mike
LVL 1
mikeydkAsked:
Who is Participating?
 
oBdACommented:
So you want to keep a relation between the input you fed to "calc" and the results for each input value?
Don't use a two-dimensional array for that; the VBScript days are over, and rightfully so.
The following will create custom objects to return, with one property 'Value' with the original value passed to the function, and a property 'Result' with the calculated result.
$example = ("AAA", "BBB", "CCC")

Function Calc { 
	Param($Value)
	$ReturnObject = '' | Select-Object -Property 'Value', 'Result'
	$ReturnObject.Value = $Value
	$ReturnObject.Result = "test1"
	Return $ReturnObject
}

$example | % { calc -Value $_}

Open in new window

1
 
David Johnson, CD, MVPOwnerCommented:
you are moving from a 1 dimensional array to a 2 dimensional array.
0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
You mean as another "column"? That would need an array of objects, e.g. of arrays. What do you want to do with the result?
0
 
CLR BenjaminCommented:
Maybe a trick:

function calc {
    param ()
   
    return "test1"
    }

$example = ("AAA", "BBB", "CCC")
$count = $example.count
$count = $count -1
$array = 0..$count |  foreach-object{
$example[$_]| foreach-object {new-object psobject -property @{ $_ = calc $_}}
}

try

$array | select-object AAA
$array | fl
0
 
mikeydkAuthor Commented:
David Johnson, CD, MVP> Yes ;)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.