我想知道是否有人能帮助我理解为什么System.IO.FileInfo在处理相对路径时在Windows上的行为与在Linux上的行为不同。
示例
PS /home/user/Documents> ([System.IO.FileInfo]'./test.txt').FullName
/home/user/Documents/test.txtWindows上的
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(...)块以接受这两种情况(绝对和相对)的最佳方法是什么。我过去常常将path参数输入到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
}发布于 2022-03-29 15:21:55
最简单的选择是使用Convert-Path来:
兼容。
如果我们使用[cmdletbinding()],另一个很好的选择是使用$PSCmdlet.GetUnresolvedProviderPathFromPSPath(..) method。
function ResolvePath {
[cmdletbinding()]
param($path)
$PSCmdlet.GetUnresolvedProviderPathFromPSPath($path)
}
ResolvePath \\server01\test # => \\server01\test
ResolvePath C:\Users\user\Documents # => C:\Users\user\Documents
ResolvePath C:Documents # => C:\Documents
(ResolvePath .) -eq $PWD.Path # => True
(ResolvePath ~) -eq $HOME # => True发布于 2022-07-19 07:58:54
另一种选择:
由于您希望将强制转换的结果转换为[System.IO.FileInfo],所以可以使用Get-Item,这也将返回[System.IO.FileInfo]对象,但可以按照预期使用解析的相对路径。它还将包含一些错误检测(无效字符或不存在的路径等)。
示例:
PS C:\Users\User\Documents> (Get-Item -LiteralPath '.\test.txt').FullName
C:\Users\User\Documents\test.txthttps://stackoverflow.com/questions/70254096
复制相似问题