I have no idea what you do with your scripts, but I often work with paths. Sometimes I need a drive letter and other times a file name or the folder where everything is located. And a while ago I had an issue where I needed to see quickly de extensions of a long list of files. But how do you extract that information from a path easily and quickly? Read on quickly to see some possibilities.

Let’s start with a path first.

$path = "C:\users\user01\pictures\screenshots\important.png"

We could do split on the path and take the parts we want. Like we do here below:

$PartsOfThePath = $path.split('\')

$PartsOfThePath[-1] ## important.png
$PartsOfThePath[0] ## C:
$PartsOfThePath[0..2] -join '\' ## C:\users\user01

But this is a tedious job. There is a better and easier way with Split-Path.

Split-Path

With Split-Path we can do a lot of nice things

Split-Path -Path $path -Qualifier ## C:
Split-Path -Path $path -NoQualifier ## \users\user01\pictures\screenshots\important.png

Split-Path -Path $path -Leaf ## important.png
Split-Path -Path "...\screenshots\*.png" -Leaf ## *.png
Split-Path -Path "...\screenshots\*.png" -Leaf -Resolve ## important.png, check_this.png

Split-Path -Path $path -LeafBase ## important (Added in PowerShell 6.0)
Split-Path -Path $path -Extension ## .png (Added in PowerShell 6.0)

Split-Path -Path $path -Parent ## C:\users\user01\pictures\screenshots

Split-Path -Path $path -IsAbsolute ## True

Some parameters are worth explaining a bit further.

-IsAbsolute

If the path is absolute (on Windows, an absolute path string must start with a provider drive specifier, like C: or HKCU:), this cmdlet returns $true

if the path is relative, the path starts with a dot (.) or a dot-dot (..), this cmdlet returns $false

-Resolve

The parts of the path that contain a wildcard or a variable are resolved to the actual value.

-Leaf

Using Leaf returns the last part of the path and can be a file or a directory.

Making combinations

$path = "C:\users\user01\pictures\screenshots\important.png"

Split-Path (Split-Path $path -Parent) -Leaf ## screenshots

(Split-Path C:\Windows\system32) + '\' + (Split-Path $home\documents\test.txt -Leaf) ## C:\Windows\test.txt

Leave a Reply

Your email address will not be published. Required fields are marked *