Powershell: resolve path that might not exist?

前端 未结 13 2467
再見小時候
再見小時候 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:31

    You can just set the -errorAction to "SilentlyContinue" and use Resolve-Path

    5 >  (Resolve-Path .\AllFilerData.xml -ea 0).Path
    C:\Users\Andy.Schneider\Documents\WindowsPowerShell\Scripts\AllFilerData.xml
    
    6 >  (Resolve-Path .\DoesNotExist -ea 0).Path
    
    7 >
    
    0 讨论(0)
  • 2020-12-02 13:38
    function Get-FullName()
    {
        [CmdletBinding()]
        Param(
            [Parameter(ValueFromPipeline = $True)] [object[]] $Path
        )
        Begin{
            $Path = @($Path);
        }
        Process{
            foreach($p in $Path)
            {
                if($p -eq $null -or $p -match '^\s*$'){$p = [IO.Path]::GetFullPath(".");}
                elseif($p -is [System.IO.FileInfo]){$p = $p.FullName;}
                else{$p = [IO.Path]::GetFullPath($p);}
                $p;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 13:40

    I've found that the following works well enough.

    $workingDirectory = Convert-Path (Resolve-Path -path ".")
    $newFile = "newDir\newFile.txt"
    Do-Something-With "$workingDirectory\$newFile"
    

    Convert-Path can be used to get the path as a string, although this is not always the case. See this entry on COnvert-Path for more details.

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

    I had a similar issue where I needed to find the folder 3 levels up from a folder that does not exist yet to determine the name for a new folder I wanted to create... It's complicated. Anyway, this is what I ended up doing:

    ($path -split "\\" | select -SkipLast 3) -join "\\"
    
    0 讨论(0)
  • 2020-12-02 13:43

    There is an accepted answer here, but it is quite lengthy and there is a simpler alternative available.

    In any recent version of Powershell, you can use Test-Path -IsValid -Path 'C:\Probably Fake\Path.txt'

    This simply verifies that there are no illegal characters in the path and that the path could be used to store a file. If the target doesn't exist, Test-Path won't care in this instance -- it's only being asked to test if the provided path is potentially valid.

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

    You want:

    c:\path\exists\> $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath(".\nonexist\foo.txt")
    

    returns:

    c:\path\exists\nonexists\foo.txt
    

    This has the advantage of working with PSPaths, not native filesystem paths. A PSPAth may not map 1-1 to a filesystem path, for example if you mount a psdrive with a multi-letter drive name.

    -Oisin

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