views:

1658

answers:

6

I have two paths:

fred\frog

and

..\frag

I can join them together in PowerShell like this:

join-path 'fred\frog' '..\frag'

That gives me this:

fred\frog\..\frag

But I don't want that. I want a normalized path without the double dots, like this:

fred\frag

How can I get that?

A: 

Well, one way would be:

Join-Path 'fred\frog' '..\frag'.Replace('..', '')

Wait, maybe I misunderstand the question. In your example, is frag a subfolder of frog?

EBGreen
"is frag a subfolder of frog?" No. The .. means go up one level. frag is a subfolder (or a file) in fred.
dangph
A: 

If you need to get rid of the .. portion, you can use a System.IO.DirectoryInfo object. Use 'fred\frog..\frag' in the constructor. The FullName property will give you the normalized directory name.

The only drawback is that it will give you the entire path (e.g. c:\test\fred\frag).

Dan R
+2  A: 

You could also use Path.GetFullPath, although (as with Dan R's answer) this will give you the entire path. Usage would be as follows:

[IO.Path]::GetFullPath( "fred\frog\..\frag" )

or more interestingly

[IO.Path]::GetFullPath( (join-path "fred\frog" "..\frag") )

both of which yield the following (assuming your current directory is D:\):

D:\fred\frag

Note that this method does not attempt to determine whether fred or frag actually exist.

Charlie
That's getting close, but when I try it I get "H:\fred\frag" even though my current directory is "C:\scratch", which is wrong. (It shouldn't do that according to the MSDN.) It gave me an idea however. I'll add it as an answer.
dangph
A: 

This gives the full path:

(gci 'fred\frog\..\frag').FullName

This gives the path relative to the current directory:

(gci 'fred\frog\..\frag').FullName.Replace((gl).Path + '\', '')

For some reason they only work if frag is a file, not a directory.

dangph
gci is an alias for get-childitem. The children of a directory are its contents. Replace gci with gi and it should work for both.
zdan
+4  A: 

You can expand ..\frag to its full path with resolve-path:

PS > resolve-path ..\frag

Try to normalize the path using the combine() method:

[io.path]::Combine("fred\frog",(resolve-path ..\frag).path)

Shay Levy
A: 

This library is good: NDepend.Helpers.FileDirectoryPath.

dangph
I don't know why that got a downvote. That library really is good for doing path manipulations. It's what I ended up using in my project.
dangph