我正在使用psake编写构建脚本,我需要从当前工作目录创建一个绝对路径,输入路径可以是相对路径,也可以是绝对路径。
假设当前位置是C:\MyProject\Build
$outputDirectory = Get-Location | Join-Path -ChildPath ".\output"给出了C:\MyProject\Build\.\output,这并不可怕,但我希望没有.\。我可以使用Path.GetFullPath来解决这个问题。
当我想要提供绝对的路径时,问题就出现了。
$outputDirectory = Get-Location | Join-Path -ChildPath "\output"给出了C:\MyProject\Build\output,在这里我需要C:\output。
$outputDirectory = Get-Location | Join-Path -ChildPath "F:\output"给出了C:\MyProject\Build\F:\output,在这里我需要F:\output。
我尝试使用Resolve-Path,但这总是抱怨路径不存在。
我假设Join-Path不是可以使用的cmdlet,但是我还没有找到任何关于如何做我想做的事情的资源。有一条简单的单行来完成我需要的东西吗?
发布于 2015-03-21 23:24:01
您可以使用GetFullPath(),但需要使用"hack“使其将当前位置用作当前目录(解析相对路径)。在使用修复之前,.NET方法的当前目录是进程的工作目录,而不是您在PowerShell进程中指定的位置。请参阅Why don't .NET objects in PowerShell use the current directory?
#Hack to make .Net methods use the shells current directory instead of the working dir for the process
[System.Environment]::CurrentDirectory = (Get-Location)
".\output", "\output", "F:\output" | ForEach-Object {
[System.IO.Path]::GetFullPath($_)
}输出:
C:\Users\Frode\output
C:\output
F:\output像这样的东西应该对你有用:
#Hack to make .Net methods use the shells current directory instead of the working dir for the process
[System.Environment]::CurrentDirectory = (Get-Location)
$outputDirectory = [System.IO.Path]::GetFullPath(".\output")发布于 2015-03-21 23:34:21
我不认为有一条简单的单线。但是我假设你需要创建路径,如果它还不存在的话?那么,为什么不直接测试并创建它呢?
cd C:\
$path = 'C:\Windows', 'C:\test1', '\Windows', '\test2', '.\Windows', '.\test3'
foreach ($p in $path) {
if (Test-Path $p) {
(Get-Item $p).FullName
} else {
(New-Item $p -ItemType Directory).FullName
}
}https://stackoverflow.com/questions/29188848
复制相似问题