问题
I have the following code:
$myVar = 'C:\Users\$env:USERNAME\Desktop'
Test-Path "$myVar"
The variable $myVar
is needed with single quotes to display the actual variables used to the user.
How can I then actually process the variable later into the actual path to use?
Test-Path $myVar
returns False
, not seeing the users path "C:\Users\User\Desktop"
回答1:
Found it! As the single quotes could not be changed in the original variable $myVar
, the following worked to expand its variable later:
$ExecutionContext.InvokeCommand.ExpandString($myVar)
回答2:
You should use this:
$myvar = "C:\Users\$($env:username)\Desktop"
Test-Path "$myvar"
回答3:
$myVar = "C:\Users\"+$env:USERNAME+"\Desktop"
Test-Path $myVar
来源:https://stackoverflow.com/questions/59480435/powershell-convert-string-with-env-variable