Question:
I’ve started working with Powershell lately on my Windows 10 system. I’ve created a profile file, and I wanted to put in a variable which links to a folder in my documents section. However, I didn’t want to hard-code the path because I knew I’d need to go in and re-write it if my profile name got changed in a hard drive transfer like it did the last time I sent it in for repairs. So my first thought was to put in something like this:
1 2 |
$Var = $(~\Documents\Folder) |
But that spat back an error. Then I learned of the Resolve-Path Cmdlet, which appeared at a glance to be what I needed. However, when I did this:
1 2 |
$Var = $(Resolve-Path ~\Documents\Folder) |
… I got this:
1 2 3 4 5 6 7 8 |
>$Var Path ---- C:\Users\Username\Documents\Folder > |
Which seemed like a problem. However, when I tried to cd $Var
, it worked successfully, which confused me greatly. I figured that the extraneous Path
header in the result would cause an error.
What exactly does Resolve-Path
do, and why does it still get interpreted correctly when passed into cd
? And additionally, is there any way to make Resolve-Path
not include the extraneous information and return only the expanded path?
Answer:
The reason you are seeing the header Path
is because Resolve-Path
is returning an object of type System.Management.Automation.PathInfo
and when this is not captured into a variable it is outputted as a string to the console in a readable format IE:
1 2 3 4 |
ObjProperty1 ObjProperty2 ObjProperty3 ... --------- --------- --------- ... Value1 Value2 Value3 ... |
This object works with cd
as PowerShell
is smart enough to parse the object ($var
) before cd
is run. PowerShell
will return the value of the path property to cd
meaning cd
will see a string "C:\Users\Username\Documents\Folder"
and not the object headers.
If you want to just return the path without the header use the Select
cmdlet’s -ExpandProperty
parameter:
1 2 |
$var = Resolve-Path '~\Documents\Folder' | select -ExpandProperty Path |
If you would like more information on Resolve-Path
MSDN is a good place to start (link).