Getting just the lowest-level directory name for a file from split-path using PowerShell
I need to get just the last part of the path name for a file.
Example:
c:\dir1\dir2\dir3\file.txt
I need to get dir3
into a variable.
I have been trying with Split-Path
, but it gives me the whole path.
Solution 1:
This takes two invocations of Split-Path
AFAICT:
PS> Split-Path (Split-Path c:\dir1\dir2\dir3\file.txt -Parent) -Leaf
dir3
Solution 2:
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"))
Solution 3:
If you want to keep it simple and the path is going to be in normal form, you can use String.Split()
:
"c:\dir1\dir2\dir3\file.txt".split("\")[-2]