简体   繁体   English

Powershell v4和v5之间的Join-Path cmdlet的行为

[英]Behaviour of Join-Path cmdlet between Powershell v4 and v5

I'm executing the following command on a machine where G: drive does not exist: 我正在G:驱动器不存在的机器上执行以下命令:

Join-Path "G:\" "abc.txt"

In Powershell v5, this returns "G:\\abc.txt" as expected. 在Powershell v5中,按预期返回“G:\\ abc.txt”。 I simply want to join sub-paths and not validate it's existence. 我只是想加入子路径而不是验证它的存在。 On the other hand, in Powershell v4, it fails with the following error: 另一方面,在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

For some reasons I am stuck with using Powershell v4 and cannot make a move to Powershell v5 right now. 出于某些原因,我坚持使用Powershell v4,现在无法转向Powershell v5。 Is there any out-of-the-box solution for simply joining sub-paths in Powershell v4 or do I need to create a custom solution? 是否有任何开箱即用的解决方案,只需在Powershell v4中加入子路径,或者我是否需要创建自定义解决方案?

No way. 没门。 It's by design ( I've not tested it on version 5.0) 这是设计(我没有在5.0版本上测试过它)

You need to concat strings and eventually cast to [System.IO.fileinfo] : 你需要连接字符串并最终转换为[System.IO.fileinfo]

$a = 'G:\'
$b = 'abc.txt'
$mypath = [system.io.fileinfo]($a.TrimEnd('\') + '\' +  $b.TrimStart('\'))

Link on microsoft connect 微软连接上的链接

from get-help join-path -full : 来自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.

To avoid the exists check, you can use Path.Combine() : 要避免存在检查,可以使用Path.Combine()

PS C:\> [System.IO.Path]::Combine('G:\','nonexistingfile.txt')
G:\nonexistingfile.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM