BHustus BHustus - 10 months ago 59
PowerShell Question

What exactly does the Resolve-Path cmdlet do?

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:

$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:

$Var = $(Resolve-Path ~\Documents\Folder)

... I got this:




Which seemed like a problem. However, when I tried to
cd $Var
, it worked successfully, which confused me greatly. I figured that the extraneous
header in the result would cause an error.

What exactly does
do, and why does it still get interpreted correctly when passed into
? And additionally, is there any way to make
not include the extraneous information and return only the expanded path?


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:

 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:

$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).