Powershell Convert String With ENV Variable

纵然是瞬间 提交于 2021-02-10 08:39:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!