Join-Path Fails with Nonexistent Drives

by Nov 25, 2014

All Versions

To construct path names from parent folders and files, you may have been using Join-Path. This cmdlet takes care of the correct number of backslashes when you combine path components:

$part1 = 'C:\somefolder\'
$part2 = '\myfile.txt'
$result = Join-Path -Path $part1 -ChildPath $part2

$result 

However, Join-Path will fail if the path components do not exist. So you cannot create a path for a drive that is not mounted:

$part1 = 'L:\somefolder\'
$part2 = '\myfile.txt'
$result = Join-Path -Path $part1 -ChildPath $part2

$result
  
Join-Path : Cannot find drive. A drive with the name 'L' does not exist. 

In essence, what Join-Path does can be done manually as well. This will combine two path segments and take care of backslashes:

$part1 = 'L:\somefolder\'
$part2 = '\myfile.txt'
$result = $part1.TrimEnd('\') + '\' +  $part2.TrimStart('\')

$result 

If you have enabled the Hyper-V module for PowerShell in the Windows features (like outlined in a previous tip), you can now manage virtual disks from PowerShell.

Twitter This Tip! ReTweet this Tip!