Split Path - PowerShell


Overview

Split-Path is a PowerShell command that parses a specified path into its individual components, such as the drive, directory, filename, and extension. It is typically used to extract specific parts of a path for further processing or manipulation.

Syntax

Split-Path [-LiteralPath] <String> [-PathType <PathType>] [-Resolve]

Parameters:

| Parameter | Description |
|—|—|
| -LiteralPath | Optional. Treats the input string as a literal path instead of trying to resolve it. |
| | Required. The path to parse. |
| -PathType | Optional. Specifies the type of path to return. Possible values are: “Drive”, “Directory”, “FilePath”, “LeafName”, and “Extension”. |
| -Resolve | Optional. Resolves the supplied path to a fully qualified path. |

Options/Flags

| Option | Description |
|—|—|
| -Directory | Returns only the directory portion of the path. |
| -Drive | Returns only the drive portion of the path. |
| -FilePath | Returns the full path without the leaf name. |
| -Extension | Returns only the extension of the leaf name. |
| -LeafName | Returns only the leaf name (filename with extension). |

Examples

Example 1: Extracting the filename and path separately

$path = "C:\Users\admin\Desktop\test.txt"
$filename = Split-Path $path -LeafName
$dir = Split-Path $path -Directory

Example 2: Resolving a relative path to a fully qualified path

$path = ".\test.txt"
$resolvedPath = Split-Path $path -Resolve

Common Issues

  • If the input path is invalid or contains special characters, errors may occur. Use the -LiteralPath parameter to treat the path as a literal string.
  • If the -PathType parameter is unspecified, the default is “FilePath”, which includes the leaf name and extension.

Integration

  • Use Split-Path with Join-Path to combine path components into a fully qualified path.
  • Pipe the output of Split-Path to Test-Path to check if a specific path component exists.
  • Combine Split-Path with Get-ChildItem to filter items based on their path type (e.g., files, directories).
  • Get-ChildItem
  • Join-Path
  • Test-Path