考虑以下情况:我有一个参数或配置变量,用于设置脚本的输出目录。显然,这个参数也应该能够是绝对的:
RepoBackup.ps1 -OutputDirectory .\out
RepoBackup.ps1 -OutputDirectory D:\backup
在脚本中,我结合使用(Get-Item -Path './').FullName
和Join-Path
来确定输出目录的绝对路径,因为我可能需要使用Set-Location
来更改当前目录-这使得使用相对路径变得复杂。
但是:
Join-Path C:\code\ .\out # => C:\code\.\out (which is exactly what i need)
Join-Path C:\code\ D:\ # => C:\code\D:\ (which is not only not what i need, but invalid)
我考虑过使用Resolve-Path
并执行类似Resolve-Path D:\backup
的操作,但如果该目录不存在(目前还不存在),则会产生无法找到路径的错误。
那么,如何获得$OutputDirectory
的绝对路径,同时接受绝对和相对输入,以及尚不存在的路径呢?
发布于 2020-12-01 17:15:00
这个函数为我完成了这项工作:
function Join-PathOrAbsolute ($Path, $ChildPath) {
if (Split-Path $ChildPath -IsAbsolute) {
Write-Verbose ("Not joining '$Path' with '$ChildPath'; " +
"returning the child path as it is absolute.")
$ChildPath
} else {
Write-Verbose ("Joining path '$Path' with '$ChildPath', " +
"child path is not absolute")
Join-Path $Path $ChildPath
}
}
# short version, without verbose messages:
function Join-PathOrAbsolute ($Path, $ChildPath) {
if (Split-Path $ChildPath -IsAbsolute) { $ChildPath }
else { Join-Path $Path $ChildPath }
}
Join-PathOrAbsolute C:\code .\out # => C:\code\.\out (just the Join-Path output)
Join-PathOrAbsolute C:\code\ D:\ # => D:\ (just the $ChildPath as it is absolute)
它只检查后一个路径是否是绝对路径,如果是,就返回它,否则它只在$Path
和$ChildPath
上运行Join-Path
。请注意,这并没有将基础$Path
视为相对的,但对于我的用例来说,这已经足够了。(我使用(Get-Item -Path './').FullName
作为基本路径,这无论如何都是绝对的。)
Join-PathOrAbsolute .\ D:\ # => D:\
Join-PathOrAbsolute .\ .\out # => .\.\out
请注意,虽然.\.\
和C:\code\.\out
看起来确实很奇怪,但它是有效的,并且可以解析为正确的路径。毕竟,这只是PowerShell集成的Join-Path
函数的输出。
https://stackoverflow.com/questions/65086428
复制相似问题