0

Task: make PowerShell 5 to read/activate user input that contains any variable. This doesn't work on both script defined and environment variables. E.g.:

$H=4
$testParA=Read-Host "Try to input enviroment variable `$Env:windir :" #user input is $H
$testParB=Read-Host "Try to input variable `$H :" #user input is $H

Write-Host $testParA
Write-Output $testParA

Write-Host $testParB
Write-Output $testParB

Result:

> $Env:windir
> $Env:windir
> $H
> $H

Expectation:

> C:\Windows
> C:\Windows
> 4
> 4

Original task: In a text generator PowerShell script, let users to customize text, and where to place the serial counter variable "$serial". E.g., "some text $serial some other text"

No-duplication: This question has been marked as duplicate from "https://stackoverflow.com/questions/1667023/expanding-variables-in-file-contents", but not really. The answer is surely duplicated, but the question part is very different (You have to know "expand variables" to be able to find this question from searching, which is why I was unable to get answers before posting this question), and could have other methods to achieve the same or a better result. In general, on closing this question will only cause more people who never heared of "expand variables" to further create similar questions. There is probably a better method than simply closing this question.

  • There is a similar problem, but it's currently out of answers: https://stackoverflow.com/questions/62479253/user-input-into-variable-containing-special-characters-and-wild-cards-not-passin – JC Gong Avoe Dec 19 '22 at 01:37
  • `$ExecutionContext.InvokeCommand.ExpandString($testParA)` to expand it – Santiago Squarzon Dec 19 '22 at 01:42
  • It works! You could post at answer area, and I'll mark as "Answered" for you. – JC Gong Avoe Dec 19 '22 at 01:50
  • What you want to do is to expand the value of a variable from string which is what `Read-Host` always outputs and why `$H` is not expanded by default so the question is a duplicate. If your intent is to just input variable names and expand them you can just `Get-Variable $testParA.TrimStart('$')` – Santiago Squarzon Dec 19 '22 at 02:18

0 Answers0