Getting just the lowest-level directory name for a file from split-path using PowerShell
This takes two invocations of Split-Path
AFAICT:
PS> Split-Path (Split-Path c:\dir1\dir2\dir3\file.txt -Parent) -Leaf
dir3
This question is specifically asking for split-path it seems, but some other ways are:
If the file exists, I find it is much nicer to do:
(Get-Item c:\dir1\dir2\dir3\file.txt).Directory.Name
If the file does not exist, this won't work. Another way in that case is to use the .NET API, for example:
$path = [System.IO.Path];
$path::GetFileName($path::GetDirectoryName("c:\dir1\dir2\dir3\file.txt"))
Another option using System.Uri:
PS> ([uri]"c:\dir1\dir2\dir3\file.txt").segments[-2].trim('/')
dir3
And if the file exists on disk:
PS> (dir c:\dir1\dir2\dir3\file.txt).directory.name