If $fileName exists then the cmdlet equivalent of [System.IO.Path]::GetFullPath($fileName);
is (Get-Item $fileName).FullName
. Howev开发者_运维百科er, 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>
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.
You can remove the drive qualifier of 'c:\config.sys' (Using Split-Path) and then join the two paths:
PS > Join-Path $pwd (Split-Path 'c:\config.sys' -NoQualifier)
C:\Users\zippy\Documents\deleteme\config.sys
精彩评论