2

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 "^.*?\\"; " "}}
  • 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 '21 at 09:01

2 Answers2

4

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.

Peter Hahndorf
  • 13,763
  • 3
  • 37
  • 58
2

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

Tobias
  • 1,236
  • 13
  • 25