18

So I have this code:

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

I would expect output of the below from $localpath:

c:\users\username\some\path

However what I get is:

System.Collections.DictionaryEntry\some\path

So, of course, something like cd $localpath fails. How would I accomplish what I need?

2 Answers 2

30

A convenient way to obtain the string value rather than the dictionary entry (which is technically what Get-ChildItem is accessing) is to just use the variable syntax: $Env:USERPROFILE rather than Get-ChildItem Env:USERPROFILE.

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

For more information:

PowerShell Environment Provider

about_Environment_Variables

Also, the Join-Path cmdlet is a good way to combine two parts of a path.

$localpath = Join-Path $env:USERPROFILE 'some\path'
Sign up to request clarification or add additional context in comments.

2 Comments

@AnsgarWiechers Thanks for the thoughtful edit providing examples.
If you come from the CMD-heavy world of Windows Scripting, don't forget to include $ in you setter name. In CMD, Set varname=something would have to be, $varname=something, not varname=something.
1

Late to the party and apart from whether the example is a good way of getting an environment variable, the actual answer to the question is this:

$userprofile = Get-ChildItem Env:USERPROFILE
$localpath="$($userprofile.Value)\some\path"

This might be functionality of newer versions of Powershell since the original question though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.