I need to get only the nearest subdirectory and file name from the file path as follows.


(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 "^.*?\\"; " "}}
  • on a file object, you have a property named >>> .Directory.Parent <<< that will give you the parent dir of the current dir. a similar property exists on directory objects >>> .Parent <<< ///// that can chain all the way up your dir tree ... [grin] – Lee_Dailey May 12 at 9:01

You could use the Directory property of the object:

Get-ChildItem $directoryPath -Recurse -File | ForEach-Object {
    "$($_.FullName) - $($_.Directory.Name)\$($_.Name)"

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:

$splitString = "E:\Dump\SubDump3\Sub_SubDump1\DumpText-1.txt" -split "\\"

(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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.