Powershell v4 和 v5 之间的 Join-Path cmdlet 行为
Behaviour of Join-Path cmdlet between Powershell v4 and v5
我正在 G:
驱动器不存在的机器上执行以下命令:
Join-Path "G:\" "abc.txt"
在 Powershell v5 中,这 returns "G:\abc.txt" 符合预期。我只是想加入子路径而不验证它的存在。
另一方面,在 Powershell v4 中,它失败并出现以下错误:
Join-Path : Cannot find drive. A drive with the name 'G' does not exist.
At line:1 char:1
+ Join-Path "G:\" "abc.txt"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (G:String) [Join-Path], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand
出于某些原因,我一直坚持使用 Powershell v4,现在无法迁移到 Powershell v5。是否有任何开箱即用的解决方案可以简单地加入 Powershell v4 中的子路径,或者我是否需要创建自定义解决方案?
没办法。这是设计使然(我没有在 5.0 版上测试过)
您需要连接字符串并最终转换为 [System.IO.fileinfo]
:
$a = 'G:\'
$b = 'abc.txt'
$mypath = [system.io.fileinfo]($a.TrimEnd('\') + '\' + $b.TrimStart('\'))
来自 get-help join-path -full
:
The Join-Path cmdlet is designed to work with the data exposed by any provider. To list the providers
available in your session, type "Get-PSProvider". For more information, see about_Providers.
要避免存在检查,您可以使用 Path.Combine()
:
PS C:\> [System.IO.Path]::Combine('G:\','nonexistingfile.txt')
G:\nonexistingfile.txt
我正在 G:
驱动器不存在的机器上执行以下命令:
Join-Path "G:\" "abc.txt"
在 Powershell v5 中,这 returns "G:\abc.txt" 符合预期。我只是想加入子路径而不验证它的存在。 另一方面,在 Powershell v4 中,它失败并出现以下错误:
Join-Path : Cannot find drive. A drive with the name 'G' does not exist.
At line:1 char:1
+ Join-Path "G:\" "abc.txt"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (G:String) [Join-Path], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand
出于某些原因,我一直坚持使用 Powershell v4,现在无法迁移到 Powershell v5。是否有任何开箱即用的解决方案可以简单地加入 Powershell v4 中的子路径,或者我是否需要创建自定义解决方案?
没办法。这是设计使然(我没有在 5.0 版上测试过)
您需要连接字符串并最终转换为 [System.IO.fileinfo]
:
$a = 'G:\'
$b = 'abc.txt'
$mypath = [system.io.fileinfo]($a.TrimEnd('\') + '\' + $b.TrimStart('\'))
来自 get-help join-path -full
:
The Join-Path cmdlet is designed to work with the data exposed by any provider. To list the providers
available in your session, type "Get-PSProvider". For more information, see about_Providers.
要避免存在检查,您可以使用 Path.Combine()
:
PS C:\> [System.IO.Path]::Combine('G:\','nonexistingfile.txt')
G:\nonexistingfile.txt