Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Relative paths of all the folders, sub-folders and files in a folder

I have a folder named source. It's structure is like the following.

source\a.jpg
source\b.jpg
source\c.xml
source\d.ps1
source\subdir1\a.xml
source\subdir2\b.png
source\subdir3\subsubdir1\nothing.img

I want to list all the relative paths of folders, sub-folders and files in a text file say, out.txt. For above the output I expect is:

source\a.jpg
source\b.jpg
source\c.xml
source\d.ps1
source\subdir1\a.xml
source\subdir2\b.png
source\subdir3\subsubdir1\nothing.img
source\subdir1
source\subdir2
source\subdir3
source\subdir3\subsubdir1

You can see that the output includes individual folders and sub-folders too.

Note: I am in a folder just outside the source folder. I mean for example I am in fold folder which contains source folder -> fold/source but if your solution includes putting the script inside the source folder, thats fine too. Both solutions are fine. This may be easy but I am not familiar with powershell but can at least run scripts from it if given.

EDIT1: Okay, in the "duplicate question" the answer is for relative paths of individual files. But I also want the folders and sub-folders.

EDIT2: Okay, I wrote a command:

(gci -path source -recurse *.|Resolve-path -relative) -replace "","" | out-file -FilePath output.txt -Encoding ascii

Now, this command gives me the relative name of only subdirectory inside the source(in the actual source folder of mine with a different name; source is a dummy name obviously!). What should I change in this code to get other names of files inside the subdirectory in source.

like image 218
Manish Kumar Sharma Avatar asked Nov 22 '25 05:11

Manish Kumar Sharma


1 Answers

This is clean one line answer, with no loops on my part to write, which does the job perfectly. I produced it by luck "playing around" a bit.

(gci -Path source -Recurse *.*|Resolve-Path -Relative) -replace "\.\\","" |
  Out-File -FilePath output.txt -Encoding ascii
like image 142
Manish Kumar Sharma Avatar answered Nov 24 '25 22:11

Manish Kumar Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!