Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 532
MutantOctopus Avatar asked Dec 24 '22 02:12

MutantOctopus


2 Answers

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

like image 199
Richard Avatar answered Dec 26 '22 14:12

Richard


Easy Example for a Resolve-Path job,

Let's say you don't know the office version in your computer and want to get the correct path, Resolve-Path can help...

$TestPath = 'C:\Program Files (x86)\Microsoft Office\*\Winword.exe'
$Path = (Resolve-Path $TestPath).Path
like image 24
Avshalom Avatar answered Dec 26 '22 15:12

Avshalom