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

时间:2015-10-23 13:11:38

标签: powershell powershell-v4.0 powershell-v5.0

我正在G:驱动器不存在的机器上执行以下命令:

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

在Powershell v5中,按预期返回“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中加入子路径,或者我是否需要创建自定义解决方案?

2 个答案:

答案 0 :(得分:1)

没办法。这是设计(我没有在5.0版本上测试过)

你需要连接字符串并最终转换为[System.IO.fileinfo]

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

Link on microsoft connect

来自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.

答案 1 :(得分:1)

要避免存在检查,您可以使用Path.Combine()

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