Miquel Àngel
Miquel Àngel

Reputation: 164

How to dynamically create an array and use it in Powershell

I need to create and then use arrays but I need to create dynamically. I'm developing script to get the app pools memory, but when we have more than 1 worker process i need to store in array the memory and then calculate the average.

I'm using this to create it

New-Variable -Name "Array_$($AppPoolName)" -Value @()

But I don't know how to add data to the array using a dynamic name as I would do it when I use a fixed name ($var += <Value>).

Upvotes: 2

Views: 21837

Answers (4)

Jim
Jim

Reputation: 762

You can do this without hashtables and without Invoke-Expression:

New-Variable -Name "Array_$($AppPoolName)" -Value @()
( Get-Variable -Name "Array_$($AppPoolName)" ).Value += <Value>

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 202032

Use Get-Variable to retrieve the dynamically named variable e.g.:

$var = Get-Variable "Array_$AppPoolName" -ValueOnly
$var += <value>

For completeness you can also use Set-Variable but that doesn't directly support array concat syntax e.g.:

Set-Variable "Array_$AppPoolName" (Get-Variable "Array_$AppPoolName" -ValueOnly) += <value>)

Yeah, that's a spew. Perhaps a better option is to just use a hashtable:

$ht = @{"Array_$($AppPoolName)" = @()}
$ht."Array_$($AppPoolName)" += 1,2,3

Upvotes: 4

Adi Inbar
Adi Inbar

Reputation: 12321

You could first store the dynamic name in a variable, then use Invoke-Expression to add to the variable, as follows:

$dynamicname = "Array1_$AppPoolName"
New-Variable -Name $dynamicname -Value @()
Invoke-Expression "`$$dynamicname += 'new value'"

(Note that you don't need $() around $AppPoolName; you can interpolate the variable on its own.)

Or, you can use Invoke-Expression to re-derive the dynamic name and modify the variable that has that derived name:

New-Variable -Name "Array_$AppPoolName" -Value @()
Invoke-Expression "`$Array1_$AppPoolName += 'new value'"

Upvotes: 1

Victor Zakharov
Victor Zakharov

Reputation: 26454

You can use Get-Variable:

$var = Get-Variable -Name "Array1_$($AppPoolName)" -ValueOnly
$var += <Value>

Notice -ValueOnly at the end. Otherwise you get a variable PSObject. From technet:

The Get-Variable cmdlet gets the Windows PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter...

Upvotes: 2

Related Questions