[PowerShell] Resolve-Path Safe!

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

PS C:\dev> Resolve-Path .\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
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand

The goal for this blogpost is to find a reliable way

My first approach was


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

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
        [string] $Path

So now it works

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

About mnaoumov

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

3 Responses to [PowerShell] Resolve-Path Safe!

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

  2. There’s an easier way:

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

    This will return $null if the file doesn’t exist

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s