Home > OS >  Split literal path to get file name
Split literal path to get file name

Time:06-04

How to get file name from literal path via split-path? Why literalPath parameter set don't have -Leaf parameter?

Split-Path -LiteralPath "D:\myDir\file.txt" -Leaf

file.txt expected

CodePudding user response:

It is an unfortunate bug that -LiteralPath doesn't work with switches such as -Leaf, up to at least PowerShell 7.2.4 - see GitHub issue #8751.

However, the bug is benign, because it is fine to use the (possibly positionally implied) -Path instead, because the usual distinction between -Path (potentially wildcard-based paths) and -LiteralPath (verbatim paths) by default does not apply to the purely textual processing that Split-Path performs, as Santiago Squarzon points out.

In other words: The following should work as intended (implicitly binds the file path to the -Path parameter, positionally):

Split-Path "D:\myDir\file.txt" -Leaf # -> 'file.txt'

Conversely, this means that - by default - Split-Path does not resolve wildcard-based paths - purely textual splitting occurs:

# NO wildcard resolution (matching), despite (implied) use of -Path
Split-Path "D:\myDir\*.txt" -Leaf   # -> '*.txt'

If wildcard resolution is needed, combined the (possibly implied) -Path parameter with the -Resolve switch:

# Wildcard resolution (matching), due to use of -Resolve with (implied) -Path
Split-Path -Resolve "D:\myDir\*.txt" -Leaf   # -> 'foo.txt', 'bar.txt', ....

Note that the distinction between -Path and -LiteralPath does matter when combined with -Resolve:

  • With -Path, -Resolve performs wildcard resolution and uses the full paths of the matching files and/or directories for splitting, if any; if there are no matches, there is no output.

  • With -LiteralPath, -Resolve only resolves the verbatim input path(s) to a full path and uses the full path for splitting; if the path doesn't exist, a non-terminating error is reported.

  • Related