Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split literal path to get file name

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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) 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 -Path):

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', ....
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading