tags:

views:

64

answers:

4

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 the item may be specified with relative paths. However, Resolve-Path prints and error when used with a non-existant file.

For example, What's the simplest, cleanest way to resolve ".\newdir\newfile.txt" to "C:\Current\Working\Directory\newdir\newfile.txt" in Powershell?

Note that System.IO.Path's static method use with the process's working directory - which isn't the powershell current location.

+4  A: 

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")
Keith Hill
Right, but that has side-effects and a bit of nasty interop I'd like to avoid - I'd kind of hoped that this 'd be something powershell (which is a shell scripting language, after all) could handle natively... Anyhow, +1 for an actual option!
Eamon Nerbonne
It also has the problem whereby the $pwd may not actually be a real path on the filesystem either; for example if you mount a psdrive with a multi-letter drive name.
x0n
Good point. Of course, you can grab the .NET current dir first, then set it to a filesystem provider path (not use $pwd) and then reset current dir back to its original value.
Keith Hill
A: 

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 >
Andy Schneider
Setting the error action to 0 doesn't actually fix the problem that resolve path won't then resolve that (perfectly valid) path.
Eamon Nerbonne
A: 

Check if the file exists before resolving:

if(Test-Path .\newdir\newfile.txt) { (Resolve-Path .\newdir\newfile.txt).Path }
shane carvalho
I need to resolve both existing and non-existing files; I'll be creating the non-existant ones.
Eamon Nerbonne
+2  A: 

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

x0n
Nice. I guess I saw some similar function when looking through Reflector to ResolvePathCommand. Going through code is good for inspiration ;)
stej
Many thanks! That command may be a little longwinded, but it's *exactly* what I was looking for.
Eamon Nerbonne