我想知道是否有人能帮助我理解为什么在处理相对路径时,System.IO.FileInfo
在 Windows 和 Linux 上的行为不同。
示例
- 在 Linux 上
PS /home/user/Documents> ([System.IO.FileInfo]'./test.txt').FullName
/home/user/Documents/test.txt
- 在Windows上
PS C:\Users\User\Documents> ([System.IO.FileInfo]'.\test.txt').FullName
C:\Users\User\test.txt
编辑
为了澄清上述内容,System.IO.FileInfo
在 Windows 或 Linux 上处理相对路径没有区别。问题与 [System.IO.Directory]::GetCurrentDirectory()
未被 Push-Location
或 Set-Location
更新有关。
以下是一个简单的示例:
PS /home/user> [System.IO.Directory]::GetCurrentDirectory()
/home/user
PS /home/user> cd ./Documents/
PS /home/user/Documents> [System.IO.Directory]::GetCurrentDirectory()
/home/user
假设这是一种预期的行为,那么在脚本和函数中处理param(...)
块以接受绝对路径和相对路径的最佳方法是什么?我曾经将路径参数类型约束为System.IO.FileInfo
,但现在我可以看到这显然是错误的。
这就是我遇到的问题,但我想知道是否有更好的方法。
我相信如果使用网络路径,Split-Path -IsAbsolute
也会带来问题,请纠正我如果我错了。
param(
[ValidateScript({
if(Test-Path $_ -PathType Leaf) {
return $true
}
throw 'Invalid File Path'
})]
[string] $Path
)
if(-not (Split-Path $Path -IsAbsolute)) {
[string] $Path = Resolve-Path $Path
}
[System.IO.Path]::GetFullPath([System.IO.Path]::Combine($pwd, '.\test.txt'))
。 - Theo[IO.Path]::IsRooted(..)
吗?还是不管怎样都会执行?我猜我找不到关于FileInfo
在 Windows 和 Linux 上的行为的答案,所以你可以将其作为一个答案提出来,如果今天结束时没有人能回答另一个问题,我会接受它。谢谢 Theo。 - Santiago Squarzon