Search notes:

PowerShell cmdLet Split-Path

The split-path cmdLet allows to select parts such as directories, filenames or extensions from a path.
Unlike resolve-path, split-path also returns a value if the specified path does not point to an existing directory or file.
The type of the returned value is a string. Its value depends on the option that is passed to split-path.
If the path drive:\dirOne\dirTwo\file.ext is used in split-path, the following parts of the path are returned:
Option used Returned value Comment
drive:\dirOne\dirTwo The directory in which a file is located, or a directory's parent directory
-parent drive:\dirOne\dirTwo Requires PowerShell 6 or later
-leaf file.ext
-leafBase file Requires PowerShell 6 or later
-extension .ext Note that it also returns the dot. Requires PowerShell 6 or later
-qualifier drive:
-noQualifier \dirOne\dirTwo\file.ext
-isAbsolute $true Compare with the static method IsPathRooted() of the .NET class System.IO.Path

PowerShell 5.1: extract file base name or extension

PowerShell 5.1 does not have the -leafBase or extension option. But it is still possible to get a file's base name or extension.
The following statement uses the -replace operator to apply a regular expression that returns a file's base name, here: ghi.
(split-path /abc/def/ghi.txt -leaf )  -replace '\.[^.]*$'
Similarly, the following statement returns the extension, however, unlike -extension, without a dot (that is: txt).
(split-path /abc/def/ghi.txt -leaf )  -replace '[^.]+\.'
In order to also return the dot, the following statement can be used:
(split-path /abc/def/ghi.txt -leaf )  -replace '.*(\.[^.]+)$', '$1'

Test script

These results of the result table were obtained with the following test script:
$path = 'drive:\dirOne\dirTwo\file.ext'

#  Get directory that contains the path:
#
split-path $path
#
#  drive:\dirOne\dirTwo

#
#  Get parent directory. In case of
#  files, get directory in which file is
#  located
#
split-path $path -parent
#
#  drive:\dirOne\dirTwo

#  Get parent directory's parent directory
#
split-path (split-path $path -parent) -parent
#
#  drive:\dirOne

#  Get file name only:
#
split-path $path -leaf
#
#  file.ext

#  Get file's extension (requires Powershell 6)
#
split-path $path -extension
#
#  .ext

#  Get file name without extension:
#
#    -leafBase requires PowerShell 6.
#     Use [IO.Path]::GetFileNameWithoutExtension($path)
#     in earlier versions.
#
split-path $path -leafBase
#
#  file

#  Check if path is absolute:
#
split-path $path -isAbsolute
#
#  True

#  Get drive of path:
#
split-path $path -qualifier
#
#  drive:

#  Get entire path without drive:
#
split-path $path -noQualifier
#
#  \dirOne\dirTwo\file.ext

Github repository about-PowerShell, path: /cmdlets/path/split/go.ps1

See also

The command parameter -credential.
Powershell command noun: path

Index