Is there an powershell cmdlet equivalent of [System.IO.Path]::GetFullPath($fileName); when $fileName doesn't exist?

Justin Dearing picture Justin Dearing · Aug 24, 2011 · Viewed 11.7k times · Source

If $fileName exists then the cmdlet equivalent of [System.IO.Path]::GetFullPath($fileName); is (Get-Item $fileName).FullName. However, an exception is thrown if the path does not exist. Is their another cmdlet I am missing?

Join-Path is not acceptable because it will not work when an absolute path is passed:

C:\Users\zippy\Documents\deleteme> join-path $pwd 'c:\config.sys'
C:\Users\zippy\Documents\deleteme\c:\config.sys
C:\Users\zippy\Documents\deleteme>

Answer

manojlds picture manojlds · Aug 24, 2011

Join-Path would be the way to get a path for a non-existant item I believe. Something like this:

join-path $pwd $filename

Update:

I don't understand why you don't want to use .Net "code". Powershell is .Net based. All cmdlets are .Net code. Only valid reason for avoiding it is that when you use .Net Code, the current directory is the directory from which Powershell was started and not $pwd

I am just listing the ways I believe this can be done so that you can handle absolute and relateive paths. None of them seem simpler than the GetFullPath() one:

$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($filename)

If you are worried if absolute path is passed or not, you can do something like:

if(Split-Path $filename -IsAbsolute){
    $filename
}
else{
    join-path $pwd $filename  # or join-path $pwd (Split-Path -Leaf $filename)
}

This is the ugly one

 $item = Get-Item $filename -ea silentlycontinue
 if (!$item) {
 $error[0].targetobject
 } else{
 $item.fullname
 }

Similar question, with similar answers: Powershell: resolve path that might not exist?