Powershell 将环境变量与路径连接起来

Powershell concatenate an Environment variable with path

所以我有这个代码:

$userprofile=Get-ChildItem Env:USERPROFILE
$localpath="$userprofile\some\path"

我希望 $localpath 的输出如下:

c:\users\username\some\path

然而我得到的是:

System.Collections.DictionaryEntry\some\path

所以,当然,cd $localpath 之类的东西会失败。我将如何完成我需要的?

获取字符串值而不是字典条目(从技术上讲是 Get-ChildItem 正在访问的内容)的一种简便方法是仅使用变量语法:$Env:USERPROFILE 而不是 Get-ChildItem Env:USERPROFILE.

$localpath = "$env:USERPROFILE\some\path"

更多信息:

PowerShell Environment Provider

about_Environment_Variables

此外,Join-Path cmdlet 是组合路径的两个部分的好方法。

$localpath = Join-Path $env:USERPROFILE 'some\path'