为什么 PowerShell 在此命令中的 %USERPROFILE% 前面插入当前工作目录路径?

blu*_*are 6 powershell environment-variables

情况是这样的:

PS C:\Users\user> copy %USERPROFILE%\AppData\Local\Thing %USERPROFILE%\AppData\Local\Thing.backup


copy : Cannot find path 'C:\Users\user\%USERPROFILE%\AppData\Local\Thing' because it does not 
exist.
At line:1 char:1
+ copy %USERPROFILE%\AppData\Local\Thing %USERPROFILE%\AppData\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\user...\Thing:String) [Copy-Item], ItemN 
   otFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
Run Code Online (Sandbox Code Playgroud)

它在文字 %USERPROFILE% 前面插入扩展的 %USERPROFILE%。

它在做什么?我怎样才能防止这种情况发生?

Was*_*sif 11

在 powershell 中你需要使用$env:UserProfile

copy "$($env:USERPROFILE)\AppData\Local\Thing" "$($env:USERPROFILE)\AppData\Local\Thing.backup"
Run Code Online (Sandbox Code Playgroud)
  • 要将字符串与变量连接起来,您需要使用自表达式运算符$()
  • 实际上copy是 powershell Cmdlet 的别名Copy-Item

旁注:如果您需要使用文字,'%USERPOFILE%'请使用-LiteralPath或使用单引号。

  • 您不需要[子表达式运算符](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7#subexpression-operator-- ) `$()` 与 `$env:<variable>` 或扩展字符串中的其他字符串变量 --- `"$env:UserProfile\Documents"` 就是您所需要的。您只需要它来访问对象变量的属性或评估更复杂的表达式:“$env:UserProfile\$($MyObject.FolderName)”。 (3认同)