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>
This method uses the current directory and current volume information to fully qualify path . If you specify a file name only in path , GetFullPath returns the fully qualified path of the current directory. If you pass in a short file name, it is expanded to a long file name.
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?
You could use the Test-Path cmdlet to check it exists before getting the fullname.
if (Test-Path $filename) {(Get-Item $fileName).FullName}
EDIT:
Just seen your comment above about Test-Path being the equivalent to the [system.io.file]::exists() function and I believe I understand your question better now.
No is the answer as I see it but you could make your own.
function Get-Fullname {
param($filename)
process{
if (Test-Path $filename) {(Get-Item $fileName).FullName}
}
}
you could tidy it up some by making the parameters accept pipeline, both strings and properties but it serves the purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With