I need to get only the nearest subdirectory and file name from the file path as follows.
Ex:-
(1)E:\Dump\DumpText-1.txt - Dump\DumpText-1.txt
(2)E:\Dump\SubDump1\DumpText-1.txt - SubDump1\DumpText-1.txt
(3)E:\Dump\SubDump3\Sub_SubDump1\DumpText-1.txt -Sub_SubDump1\DumpText-1.txt
My PowerShell Script as follows:
Get-ChildItem $directoryPath -Recurse | ForEach-Object -Process {if (!$_.PSIsContainer) {$_.FullName; $_.FullName -replace "^.*?\\"; " "}}
You could use the Directory property of the object:
just use the name of the Directory object and then the name of the file.
The easiest way in my eyes is to split the string at the backslashes:
(since the backslash is the escape character, it has to be escaped by a second backslash).
$splitString
now is an array of all the parts between the backslashes. Now you can access the last and the second-last part of this array by$splitString[-1]
(the filename) and$splitString[-2]
(the name of the direct parent folder).