Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A PowerShell script to list all files and folders within a directory

I've been trying to find a script that recursively prints all files and folders within a directory like this where the backslash is used to indicate directories:

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

I'm using PowerShell 3.0 and most other scripts I've found do not work (though they didn't anything like what I'm asking).

Additionally: I need it to be recursive.

like image 600
Melab Avatar asked Mar 01 '13 19:03

Melab


2 Answers

What you are likely looking for is something to help distinguish a file from a folder. Luckily there is a property call PSIsContainer that is true for folder and false for 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 the leading path information is not desirable, you can remove it easily enough using -replace:

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

Hopefully this gets you headed off in the right direction.

like image 129
Goyuix Avatar answered Oct 05 '22 00:10

Goyuix


It could be like:

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

Following the @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"
}
like image 41
CB. Avatar answered Oct 04 '22 23:10

CB.