The type of the returned value is a string. Its value depends on the option that is passed to split-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.
(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