How to split paths in PowerShell

Overview

In PowerShell, we use the Split-Path cmdlet to get any part of the path, like the parent folder, child folder, or files.

Syntax

Split-Path -Path "provide path here"

Parameters

  • Path: It accepts a path to split.
  • Leaf: It returns the last part of the given path.
  • Resolve: This parameter references the files that the split path leads to.

Return value

This returns a part of the path as a string.

Let's look at an example.

Example

In the example below, we'll create a test folder and some files in it and display them using the split path.

#!/usr/bin/pwsh -Command
#returns parent folder
Split-Path -Path "/usr/bin/pwsh"
#Creates test folder and some test files in it
New-Item -Path './test' -ItemType Directory >$null
New-Item -Path './test/test1.txt' >$null
New-Item -Path './test/test2.txt' >$null
New-Item -Path './test/test3.txt' >$null
Write-Host "-------Files in test folder-------"
#returns files in test folder
Split-Path -Path "./test/*.txt" -Leaf -Resolve

Explanation

In the above code snippet:

  • Line 4: We get the parent container of the given path using the cmdlet Split-Path.
  • Line 7–10: We create a folder test in the current directory and create some test files in it using the cmdlet New-Item.
  • Line 15: We display the files for the given path using the cmdlet Split-Path and the parameters Leaf and Resolve. The Leaf points to the last part of the path and Resolve displays the file names instead of the Path.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources