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.
The Split-Path cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a file name. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. You can use this cmdlet to get or submit only a selected part of a path.
Use Get-ChildItem to Get the Full Path of the Files in PowerShell. The Get-ChildItem cmdlet displays a list of files and directories on the specified location. You can use the -Recurse parameter to list all files and directories recursively. It also shows the sub-directories and their files.
To get folder name only in PowerShell, use Get-ChildItem – Directory parameter and select Name property to list folder name only on PowerShell console.
To display the directory content, Get-ChildItem cmdlet is used. You need to provide the path of the directory or if you are in the same directory, you need to use only Get-ChildItem directly. In the below example, we need to display the contents of the D:\temp directory.
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"))
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]
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
In general, if you want the name of the directory you are in I used this (thanks to Shay Levi for the original idea):
PS> (dir).directory.name[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With