Search code examples
powershellvariablesdynamic-variables

How can I dynamically call a variable in PowerShell?


I am creating a new variable name by combining existing variables, however, I cannot find a way to reference the new variable names dynamically through using my existing variables.

$count = 1
New-Variable -Name "Jobname$Count"

I am expecting to get "Jobname1" when I resolve dynamically with $JobName$Count.

I have tried different combinations of referencing the variable but none of them worked:

$JobName$($Count)
$JobName"$Count"
$JobName"$($Count)"
$JobName"($Count)"

How can I achieve this?


Solution

  • You already know how to dynamically create a new variable, either by using New-Variable or Set-Variable. If you want to dynamically get your variable you can either use Get-Variable or $ExecutionContext.SessionState.PSVariable.Get(..) or a much easier way would be using -PassThru:

    $count = 1
    $var = New-Variable -Name "Jobname$Count" -Value 'example' -PassThru
    $var
    
    Name                           Value
    ----                           -----
    Jobname1                       example
    
    Get-Variable "Jobname$Count"
    
    Name                           Value
    ----                           -----
    Jobname1                       example
    
    $ExecutionContext.SessionState.PSVariable.Get("Jobname$Count")
    
    Name                           Value
    ----                           -----
    Jobname1                       example