Issue combining variable and strings to create an environment variable output

New Contributor
I'm trying to combine some variable and string values in a script so that when the final environment variable is declared, PowerShell recognizes it.
For example, the output of:





Would be (as expected):


But if I try the following (or just about any variation I can think of):



$Profile = 'Profile'
$env:'User' + $Profile​



It gives an error stating the command wasn't valid, recommending I use ${}. So I try the following as the error recommends, which doesn't output anything at all:



${env:'User' + $Profile}​



I can't use something like



(Get-Item env:$UserProfile).value



because the tool running this code has the environment variables stored in it, not the system its running on.

The above examples are incredibly simplified, but they convey the operations I'm trying to complete, which is that I have a variable that will vary based on certain criteria when the script is ran that I need to account for, so that when the full environment variable is called for, it outputs the expected value.
Let me know if this helps, or if other examples are needed.
2 Replies
best response confirmed by sglines (New Contributor)



While I don't understand the use case, if you're contrived example is attempting to concatenate "User" and "Profile" whilst using $env, you can achieve this using the following (based on your initial example.)


$Profile = "Profile";
Invoke-Expression -Command "`$env:User$Profile";




That absolutely worked. I really appreciate the input!