Powershell: resolve path that might not exist?

前端 未结 13 2465
再見小時候
再見小時候 2020-12-02 13:05

I\'m trying to process a list of files that may or may not be up to date and may or may not yet exist. In doing so, I need to resolve the full path of an item, even though

相关标签:
13条回答
  • 2020-12-02 13:19

    Both most popular answers don't work correctly on paths on not existing drives.

    function NormalizePath($filename)
    {
        $filename += '\'
        $filename = $filename -replace '\\(\.?\\)+','\'
        while ($filename -match '\\([^\\.]|\.[^\\.]|\.\.[^\\])[^\\]*\\\.\.\\') {
            $filename = $filename -replace '\\([^\\.]|\.[^\\.]|\.\.[^\\])[^\\]*\\\.\.\\','\'
        }
        return $filename.TrimEnd('\')
    }
    
    0 讨论(0)
  • 2020-12-02 13:20

    Check if the file exists before resolving:

    if(Test-Path .\newdir\newfile.txt) { (Resolve-Path .\newdir\newfile.txt).Path }
    
    0 讨论(0)
  • 2020-12-02 13:28

    I ended up with this code in my case. I needed to create a file later in the the script, so this code presumes you have write access to the target folder.

    $File = ".\newdir\newfile.txt"
    If (Test-Path $File) {
        $Resolved = (Resolve-Path $File).Path
    } else {
        New-Item $File -ItemType File | Out-Null
        $Resolved = (Resolve-Path $File).Path
        Remove-Item $File
    }
    

    I also enclosed New-Item in try..catch block, but that goes out of this question.

    0 讨论(0)
  • 2020-12-02 13:31

    I think you're on the right path. Just use [Environment]::CurrentDirectory to set .NET's notion of the process's current dir e.g.:

    [Environment]::CurrentDirectory = $pwd
    [IO.Path]::GetFullPath(".\xyz")
    
    0 讨论(0)
  • 2020-12-02 13:31
    Join-Path (Resolve-Path .) newdir\newfile.txt
    
    0 讨论(0)
  • This has the advantage of not having to set the CLR Environment's current directory:

    [IO.Path]::Combine($pwd,"non\existing\path")
    

    NOTE

    This is not functionally equivalent to x0n's answer. System.IO.Path.Combine only combines string path segments. Its main utility is keeping the developer from having to worry about slashes. GetUnresolvedProviderPathFromPSPath will traverse the input path relative to the present working directory, according to the .'s and ..'s.

    0 讨论(0)
提交回复
热议问题