Compare paths with PowerShell

The other day I came across the need to compare two different paths for equality. The most annoying part of this task is when the paths are directories and you need to worry about the trailing slash. PowerShell provides a simple solution with minimal code.

First let’s look at the manual method

#Paths
$path1 = "C:\fake\"
$path2 = "C:\fake"

#Match path formats
if($path1.Substring($path1.Length - 1, 1).CompareTo("\") -ne 0)
{
$path1 = $path1 + "\";
}
if($path2.Substring($path2.Length - 1, 1).CompareTo("\") -ne 0)
{
$path2 = $path2 + "\";
}

#Compare paths
$path1
$path2
$path1.CompareTo($path2) -eq 0

Results

manualresults

That is a bunch of code and it took me a couple minutes to write. PowerShell’s Join-Path cmdlet, however, will handle formatting for you.

Join-Path method

#Paths
$path1 = "C:\fake\"
$path2 = "C:\fake"

#Compare paths
(Join-Path $path1 '') -eq (Join-Path $path2 '')

Results

joinpathresults

Wrap up

It is obvious that the Join-Path method is easier to remember and faster to type. I use this method every time that I compare paths, even if they are full paths with file names.

The output of the Join-Path cmdlet can seem odd when using full paths but the comparison still functions properly.

#Paths
$path1 = "C:\fake\text.txt"
$path2 = "C:\fake\text.txt"

#Compare paths
(Join-Path $path1 '')
(Join-Path $path2 '')
(Join-Path $path1 '') -eq (Join-Path $path2 '')

fullpathresults

The Join-Path cmdlet will add a backslash because it is expecting to have to separate the left and right halves of the path. This makes the path invalid, technically, but it still works for comparison purposes.

This article has 1 comment

  1. […] Derik Hammer introduces us to Join-Path: […]

Leave a Reply

%d bloggers like this: