[PowerShell] Resolve-Path Safe!

PowerShell cmdlet Resolve-Path converts from relative path to the absolute

PS C:\dev> Resolve-Path .\file-exists.txt

Path
----
C:\dev\file-exists.txt

However if we need to resolve path for non-existent file it fails

PS C:\dev> Resolve-Path .\file-not-exists.txt
Resolve-Path : Cannot find path 'C:\dev\file-not-exists.txt' because it does not exist.
At line:1 char:13
+ Resolve-Path <<<<  .\file-not-exists.txt
    + CategoryInfo          : ObjectNotFound: (C:\dev\file-not-exists.txt:String) [Resolve-Path], ItemNotFoundExceptio
   n
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand

The goal for this blogpost is to find a reliable way

My first approach was

[System.IO.Path]::GetFullPath(".\file-not-exists.txt")

But this is not right because it resolves path not from the current folder, but from the working folder where PowerShell process was started (C:\Users\Michael for me)

To fix that we need to change with working folder

[Environment]::CurrentDirectory = $PWD
[System.IO.Path]::GetFullPath(".\file-not-exists.txt")

I think that’s too much of effort for such a simple thing. And moreover who knows maybe this will affect something else

I found other interesting approaches

And I liked the top one from the link above

function Resolve-PathSafe
{
    param
    (
        [string] $Path
    )
    
    $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}

So now it works

PS C:\dev> Resolve-PathSafe .\file-not-exists.txt
C:\dev\file-not-exists.txt
Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to [PowerShell] Resolve-Path Safe!

  1. Pingback: Efficient Base64 conversion in PowerShell | mnaoumov.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s