-1

I am wondering if it is possible to reference a variable in powershell by concatonating two or more pieces of data. See example below...

$v0 = "My Var"
$v1 = "My Var2"

$suffix = 0

#THESE EXAMPLES BELOW (ALTHOUGH WRONG) WILL ILLUSTRATE WHAT WE ARE TRYING TO DO.

Write-Host $(v($suffix)) #ERROR
Write-Host $(v$suffix) #ERROR
Write-Host v$suffix # "v0"

I would like this script to output "My Var". I do not think this is possible since Powershell is using .NET which is not a dynamic language. Any ideas if this is possible?

4
  • possible duplicate of Dynamically create variables in powershell Commented Jul 10, 2013 at 16:05
  • I think in that example they are dynamically creating the name not pointing to a variable by putting together pieces of data Commented Jul 10, 2013 at 16:06
  • Write-Host (Get-Variable "v$suffix" -ValueOnly) Commented Jul 10, 2013 at 16:09
  • @JBone Think of variable, function, alias, and environment variables names as paths (similar to filename paths) in PS. You can refer 2 an item with this syntax: <provider drive>:<path name>. Get-psdrive will give you a list of <provider drive>s. Examples gi c:file.txt, gi variable:v0, gi env:path, etc. Similarly these: ${c:file.txt}, ${variable:v0}, ${env:path} also get an item. In last 2 you can omit braces. This illustrates paths but doesn't answer your question. For that u have 2 use provider specific cmdlets: get-variable and get-alias. They take names created by concatenation Commented Jul 11, 2013 at 0:18

1 Answer 1

2
Write-Host (Get-Variable "v$suffix" -ValueOnly)
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.