4

I'm executing the following command on a machine where G: drive does not exist:

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

In Powershell v5, this returns "G:\abc.txt" as expected. 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:

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. 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?

4

2 回答 2

2

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

PS C:\> [System.IO.Path]::Combine('G:\','nonexistingfile.txt')
G:\nonexistingfile.txt
于 2015-10-23T14:47:16.497 回答
1

没门。这是设计使然(我没有在 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.
于 2015-10-23T13:46:38.570 回答