How to normalize a path in PowerShell?

后端 未结 12 2101
半阙折子戏
半阙折子戏 2020-12-05 03:53

I have two paths:

fred\\frog

and

..\\frag

I can join them together in PowerShell like this:



        
12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 04:26

    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.

提交回复
热议问题