1

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?

4
  • 1
    Your first example is creating the variable $jobName1. I assume you want to dynamically call it and get it's value? Commented Mar 15, 2022 at 3:51
  • that's right, the problem is when I try to dynamically call it. EDIT: I see your point, i just changed the title of the post. thnx. Commented Mar 15, 2022 at 3:53
  • 1
    So, something like: Get-Variable -Name "$Jobname$count"? Commented Mar 15, 2022 at 3:55
  • generally speaking ... you otta not do that. [grin] use a collection and then address the objects in that collection. hashtables are REALLY good for finding something by name if the name is unique. that structure is nearly ideal for looking up stored things. Commented Mar 15, 2022 at 5:46

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

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.