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.

4
  • There is a similar problem, but it's currently out of answers: stackoverflow.com/questions/62479253/… Commented Dec 19, 2022 at 1:37
  • $ExecutionContext.InvokeCommand.ExpandString($testParA) to expand it Commented Dec 19, 2022 at 1:42
  • It works! You could post at answer area, and I'll mark as "Answered" for you. Commented Dec 19, 2022 at 1: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('$') Commented Dec 19, 2022 at 2:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.