How to normalize a path in PowerShell?

Viewed 94426

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?

13 Answers

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)

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.

Any non-PowerShell path manipulation functions (such as those in System.IO.Path) will not be reliable from PowerShell because PowerShell's provider model allows PowerShell's current path to differ from what Windows thinks the process' working directory is.

Also, as you may have already discovered, PowerShell's Resolve-Path and Convert-Path cmdlets are useful for converting relative paths (those containing '..'s) to drive-qualified absolute paths but they fail if the path referenced does not exist.

The following very simple cmdlet should work for non-existant paths. It will convert 'fred\frog\..\frag' to 'd:\fred\frag' even if a 'fred' or 'frag' file or folder cannot be found (and the current PowerShell drive is 'd:').

function Get-AbsolutePath {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]
        $Path
    )

    process {
        $Path | ForEach-Object {
            $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_)
        }
    }
}

If the path includes a qualifier (drive letter) then x0n's answer to Powershell: resolve path that might not exist? will normalize the path. If the path doesn't include the qualifier, it will still be normalized but will return the fully qualified path relative to the current directory, which may not be what you want.

$p = 'X:\fred\frog\..\frag'
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($p)
X:\fred\frag

$p = '\fred\frog\..\frag'
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($p)
C:\fred\frag

$p = 'fred\frog\..\frag'
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($p)
C:\Users\WileCau\fred\frag

This library is good: NDepend.Helpers.FileDirectoryPath.

EDIT: This is what I came up with:

[Reflection.Assembly]::LoadFrom("path\to\NDepend.Helpers.FileDirectoryPath.dll") | out-null

Function NormalizePath ($path)
{
    if (-not $path.StartsWith('.\'))  # FilePathRelative requires relative paths to begin with '.'
    {
        $path = ".\$path"
    }

    if ($path -eq '.\.')  # FilePathRelative can't deal with this case
    {
        $result = '.'
    }
    else
    {
        $relPath = New-Object NDepend.Helpers.FileDirectoryPath.FilePathRelative($path)
        $result = $relPath.Path
    }

    if ($result.StartsWith('.\')) # remove '.\'. 
    {
        $result = $result.SubString(2)
    }

    $result
}

Call it like this:

> NormalizePath "fred\frog\..\frag"
fred\frag

Note that this snippet requires the path to the DLL. There is a trick you can use to find the folder containing the currently executing script, but in my case I had an environment variable I could use, so I just used that.

If the path exists, and you don't mind returning an absolute path, you could use Join-Path with the -Resolve parameter:

Join-Path 'fred\frog' '..\frag' -Resolve

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.

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

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?

Related