How to Split Paths with the PowerShell Split-Path Cmdlet

Published:24 August 2021 - 8 min. read

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Do you need to split paths to get specific parts of it? If so, then PowerShell Split-Path is the friend you can rely on. When you work with files, certificates, and the registry, you’ll notice that paths represent their locations.

And at some point, you may need to filter which part of a path to return, perhaps when doing automation. Lucky for you, this tutorial will teach you ways to use the PowerShell Split-Path cmdlet to do so.

Come on! Keep reading, and let’s get you a new weapon for your PowerShell arsenal!

Prerequisites

If you plan to follow along with the examples in this hands-on tutorial, you’ll need a computer running any modern version of Windows that has PowerShell 5.1 or higher. This tutorial will be using Windows 10 20H2 with PowerShell 7.1.1.

What’s in a Path?

Before diving in deep with the PowerShell Split-Path cmdlet, let’s make sure that you’re clear about what a path is. A path determines the location of an item that follows a specific format.

For example, a file’s path could be C:\demo\subfolder1\TestFile_11.txt. If you separate this path into parts, the path includes the following:

  • C: is the drive or the qualifier, or the specified path. The qualifier is the part of the path from the left up to the colon (:) character.
  • \demo\subfolder1\ is the folder and subfolder(s) or containers.
  • TestFile_11.txt is the filename or the leaf. The leaf is the last element or part of a path.

Remember, though, that paths are not exclusive to files and folders. Other valid paths may include:

  • Certificate (e.g., Cert:\CurrentUser\My)
  • Registry (e.g., HKCU:\Software)
  • Function (e.g., Function:\New-Guid)
  • Variable (e.g., Variable:\PSEdition)
  • Active Directory (e.g., AD:\CN=Users,DC=Constoso,DC=com)

The PowerShell Split-Path Parameters

Like any cmdlet, Split-Path comes with a set of parameters that manipulates how the cmdlet behaves and returns its output. And these parameters are what make up the PowerShell Split-Path syntax.

  • -Path – This parameter accepts one or more path strings that you want to split. This parameter also accepts pipeline input. Wildcards in paths are also acceptable.
  • -LiteralPath – Like the -Path parameter, the -LiteralPath parameter also accepts paths to split. But this parameter will only treat the path as it is written. Meaning, the command will not interpret wildcards if you use this parameter to specify paths.
  • -Resolve – This parameter tells the Split-Path cmdlet to resolve the files or items that are referenced by the path you provided. Due to its literal nature, you cannot use this parameter together with the -LiteralPath parameter.
  • -IsAbsolute – This parameter returns a boolean value to determine whether the path you specified is an absolute path or not.

The PowerShell Split-Path cmdlet also has a parameter called -Credential, which supposedly accepts a credential PSCredential object. But according to Microsoft, this parameter is not supported by any of the out-of-the-box PowerShell providers and throws an error when you use it.

The following parameters are called the Split Location Parameters. These parameters tell the PowerShell Split-Path cmdlet which element or part of a path to return. Since the cmdlet can return only one element of a path, you can only use one of these parameters at a time.

  • -Parent – Returns the parent location (without the item or filename) of the path you specified. This parameter is also the default split location parameter, which means you can omit this parameter and still get the parent location as a result.
  • -Leaf – Returns only the last element of the path or the leaf.
  • -LeafBase – Returns only the last element of the path or the leaf without the extension. This parameter is only available in PowerShell 6.0 and above.
  • -Extension -Returns only the leaf’s extension (from the last dot “.” to the last character of the path). This parameter is only available in PowerShell 6.0 and above.
  • -Qualifier – Returns the drive or qualifier of the path only.
  • -NoQualifier – Removes the drive or qualifier from the rest of the path.

Using the PowerShell Split-Path Cmdlet (Examples)

The PowerShell Split-Path cmdlet allows you to split and dissect parts of a path. After doing so, you can specify which part of a path to return. Depending on your output requirement, you can choose to return the qualifier, path without a qualifier, and filename(s).

Getting the Parent Folder of a Path

To return the path’s parent folder, run the PowerShell Split-Path cmdlet and append the -Parent parameter.

Split-Path -Path C:\demo\subfolder1\TestFile_11.txt -Parent

The result below shows that the command returns the path of the parent folder.

Returning the parent containers of the Item
Returning the parent containers of the Item

Tip: Running the PowerShell Split-Path cmdlet without parameters will return the parent folder by default, the same behavior as using the -Parent parameter.

Tip: The -Path parameter accepts multiple paths, which allows you to split multiple paths string values in a single command.

e.g., Split-Path -Path 'c:\folder1','c:\folder2'

Displaying a Path Without the Qualifier

Imagine that you’re creating a script that duplicates a folder tree structure from one drive to another (e.g., C:\demo\subfolder1 to D:\demo\subfolder1). You might want your code to split the source path and get the folder structure only without the drive letter.

To get the path without the qualifier, run the PowerShell Split-Path cmdlet with the -NoQualifier parameter like the command below. This command splits the path while and omitting the drive letter in the result.

Split-Path -Path C:\demo\subfolder1 -NoQualifier

As you can see from the result below, using the noQualifier parameter returns path but without the qualifier string.

Returning the Path Without the Qualifier
Returning the Path Without the Qualifier

Getting the Drive or Qualifier of a Path

There may be times when you need to return the qualifier or the drive letter only. For example, when you want your script to summarize the results based on drive letters.

And to do so, run the PowerShell Split-Path command below with the -Qualifier parameter. This command will split the path and return only the qualifier string as a result.

Split-Path -Path C:\demo\subfolder1\TestFile_11.txt -Qualifier
Returning the Path's Drive or Qualifier
Returning the Path’s Drive or Qualifier

Displaying the Name of a File, Directory, or Item

Think of a path as a tree. The qualifier could is the tree itself, folders are the branches, and at the end, you’ll find the leaf. A leaf is any non-zero length string at the end of the path.

When you need to split a path to get the leaf, run the Split-Path command below and append the -Leaf parameter.

Split-Path -Path C:\demo\subfolder1\TestFile_11.txt -Leaf

As a result, the image below shows that the command only returned the filename from the path you specified.

Returning the Path's Leaf
Returning the Path’s Leaf

Splitting the Filename and Extension (≥PowerShell 6.0)

Note: This section applies to PowerShell 6.0 and above.

So you’ve split the path and returned the item. And the item, in this case, is a filename (TestFile_11.txt), which has two parts—the base and the extension. The PowerShell Split-Path cmdlet allows you to further split the leaf into these two parts with the -LeafBase and -Extension parameter.

To get the base and extension of a filename, run the commands below.

If the path does not have an extension, the Extension parameter will return an empty string.

Split-Path -Path C:\demo\subfolder1\TestFile_11.txt -LeafBase
Split-Path -Path C:\demo\subfolder1\TestFile_11.txt -Extension
Splitting the Leaf's Base and Extension
Splitting the Leaf’s Base and Extension

Splitting the Filename and Extension (≤ Windows PowerShell 5.1)

Unfortunately, the -LeafBase and -Extension parameters are not available in Windows PowerShell 5.1 and lower versions. Don’t worry though, with some PowerShell magic, you can replicate the output of these parameters even if you only have Windows PowerShell 5.1.

But instead of the Split-Path cmdlet, you’ll use the next best thing—the combination of the split() method and -replace operator.

A PowerShell string object, such as the path, contains a split() method. This method allows you to split a string into multiple elements based on a delimiter character that you provide. And in the case of paths, the delimiter is the (\\) back-slash character.

On the other hand, the -replace operator lets you replace strings using regular expressions (RegEx).

To mimic the -LeafBase parameter results, run the command below in PowerShell.

# Split the path ('C:\demo\subfolder1\TestFile_11.txt') using '\' as the delimiter.
# Select the last '[-1]' element after the split (TestFile_11.txt)
# Search the string that matches this pattern --> '\.[^.]*$'
# ^ this pattern will match the last dot "." in the path AND every other character after it.
# Then replace the match with nothing/empty value ''.
('C:\demo\subfolder1\TestFile_11.txt').split('\')[-1] -replace '\.[^.]*$',''

As a result, the screenshot below shows that the command returned only the base name of the filename.

Getting the file base in PowerShell 5.1
Getting the file base in PowerShell 5.1

Now, to get only the file extension, run the command below in PowerShell.

# Split the path ('C:\demo\subfolder1\TestFile_11.txt') using '.' as the delimiter.
# Select the last '[-1]' element after the split (txt)
('C:\demo\subfolder1\TestFile_11.txt').split('.')[-1]

The result below shows that the command returned only the filename extension – txt.

Getting the file extension in PowerShell ≤ 5.1
Getting the file extension in PowerShell ≤ 5.1

Determining if the Path is Absolute

As a system administrator, you’ll encounter two path types—absolute and relative. But what’s the difference? An absolute path begins with a qualifier, such as C:\demo or HKCU:\Software. In contrast, a relative path does not have a qualifier, like .\demo or \folder1\folder2.

The PowerShell Split-Path cmdlet can help you identify an absolute path using the -IsAbsolute parameter. To do so, run the commands below to determine whether the path is absolute.

# This path is absolute
Split-Path -Path C:\demo\subfolder1\TestFile_11.txt -IsAbsolute
# This path is relative
Split-Path -Path .\demo\subfolder1\TestFile_11.txt -IsAbsolute

As you can see below, the -isAbsolute parameter returns a boolean value to indicate whether the path is absolute (TRUE) or relative (FALSE).

Determining if the Path is Absolute
Determining if the Path is Absolute

Splitting and Resolving Paths with Wildcards

Up to this point, the paths that you split with the Split-Path cmdlet do not have to be existing ones. Whether a path exists or not, this cmdlet will split it and give you the result.

But the PowerShell Split-Path cmdlet has another parameter called -Resolve. This parameter allows you to resolve the items that are referenced by wildcards. And if you will use this parameter, the path that you will split and the items within must already exist.

For example, to return the items matching the *.txt file extension, run the command below. The -Leaf parameter ensures that the cmdlet returns only the items and not the parent containers.

The (*) wildcard represents one or more characters to match, while (?) represents a single character wildcard.

Split-Path -Path C:\demo\subfolder1\*.txt -Leaf -Resolve

The result below lists the files TestFile_11.txt through TestFile_20.txt. These files all matched the .txt filename extension.

Resolving matching filenames
Resolving matching filenames

To resolve a single character match instead, replace the asterisk (*) wildcard with the (?) wildcard, like the command below.

Split-Path -Path C:\demo\subfolder1\TestFile_2?.txt -Resolve -Leaf

The output below shows only the file TestFile_20.txt because this file is the only one that matched.

Resolving matching single character
Resolving matching single character

If the path contains an escape character, such as the grave-accent (“`), enclose the path in single quotations marks to resolve the path. For example, the command below splits and resolves a path containing an escape character.

Split-Path -Path 'C:\demo\subfolder1\dir`n\TestFile_2?.txt' -Leaf -Resolve
Splitting and Resolving a Path with Escape Characters
Splitting and Resolving a Path with Escape Characters

As a proof of concept, if you do not enclose that path in single quotation marks, the command will return an error that the path does not exist. The same error happens too if you use double quotation marks instead.

Split-Path -Path C:\demo\subfolder1\dir`n\TestFile_2?.txt -Leaf -Resolve
Split-Path -Path "C:\demo\subfolder1\dir`n\TestFile_2?.txt" -Leaf -Resolve
Resolving a Path without enclosing single quotation marks
Resolving a Path without enclosing single quotation marks

Conclusion

The PowerShell Split-Path cmdlet is an indispensable tool for system administrators and users alike. This tutorial aimed to teach you how the Split-Path cmdlet can split any given path and return specific elements based on which parameter you use.

Have you used Split-Path in your tasks before? If not, did this tutorial convince you to use it in your manual or automation jobs? Or do you know of another way to split paths better than the PowerShellSplit-Path can?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!