PowerShell script to list all files and folders in a directory

I am trying to find a script that recursively prints all files and folders in a directory like this, where a backslash is used to specify directories:

Source code\ Source code\Base\ Source code\Base\main.c Source code\Base\print.c List.txt 

I use PowerShell 3.0, and most of the other scripts I found do not work (although they did not do anything, what I ask).

Optional: I need it to be recursive.

+4
source share
7 answers

What you are most likely looking for is what helps to distinguish a file from a folder. Fortunately, there is a call to the PSIsContainer property, which is true for the folder and false for the files.

 dir -r | % { if ($_.PsIsContainer) { $_.FullName + "\" } else { $_.FullName } } C:\Source code\Base\ C:\Source code\List.txt C:\Source code\Base\main.c C:\Source code\Base\print.c 

If leading path information is undesirable, you can easily delete it using -replace :

 dir | % { $_.FullName -replace "C:\\","" } 

Hope this gets you heading in the right direction.

+8
source

It could be like:

 $path = "c:\Source code" DIR $path -Recurse | % { $_.fullname -replace [regex]::escape($path), (split-path $path -leaf) } 

Following @Goyuix idea:

 $path = "c:\source code" DIR $path -Recurse | % { $d = "\" $o = $_.fullname -replace [regex]::escape($path), (split-path $path -leaf) if ( -not $_.psiscontainer) { $d = [string]::Empty } "$o$d" } 
+4
source
 dir | % { $p= (split-path -noqualifier $_.fullname).substring(1) if($_.psiscontainer) {$p+'\'} else {$p} } 
+3
source

This one shows the full path, like some other answers, but in short:

 ls -r | % { $_.FullName + $(if($_.PsIsContainer){'\'}) } 

However, I suggest that I asked for relative paths (i.e., relative to the current directory) and only @CB answered this question. Therefore, simply by adding substring , we have the following:

 ls -r | % { $_.FullName.substring($pwd.Path.length+1) + $(if($_.PsIsContainer){'\'}) } 
+2
source
 (ls $path -r).FullName | % {if((get-item "$_").psiscontainer){"$_\"}else{$_}} 

Use only in PS 3.0

0
source

Not powershell, but you can use the following on the command line to recursively map files to a text file:

 dir *.* /s /b /a:-d > filelist.txt 
0
source

PowerShell command to list directories in a txt file:

For a complete directory of directories (folder and file) into a text file:

 ls -r | % { $_.FullName + $(if($_.PsIsContainer){'\'}) } > filelist.txt 

For a directory of relative path directories (folder and file) to a text file:

 ls -r | % { $_.FullName.substring($pwd.Path.length+1) + $(if($_.PsIsContainer){'\'}) } > filelist.txt 
0
source

All Articles