PowerShell脚本,用于列出目录中的所有文件和文件夹

Mel*_*lab 6 powershell powershell-3.0

我一直试图找到一个脚本,以递归方式打印目录中的所有文件和文件夹,其中反斜杠用于指示目录:

Source code\
Source code\Base\
Source code\Base\main.c
Source code\Base\print.c
List.txt
Run Code Online (Sandbox Code Playgroud)

我正在使用PowerShell 3.0和我发现的大多数其他脚本都不起作用(尽管他们没有像我要求的那样).

另外:我需要它是递归的.

Goy*_*uix 12

您可能正在寻找的是帮助区分文件和文件夹的内容.幸运的是,有一个属性调用PSIsContainer对于文件夹是真的,对文件是假的.

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
Run Code Online (Sandbox Code Playgroud)

如果不希望使用前导路径信息,则可以使用-replace以下方法轻松删除它 :

dir | % { $_.FullName -replace "C:\\","" }
Run Code Online (Sandbox Code Playgroud)

希望这能让你走向正确的方向.

  • 感叹号使它更正确。http://knowyourmeme.com/memes/the-1-phenomenon (3认同)

CB.*_*CB. 5

它可能是这样的:

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

遵循@Goyuix的想法:

$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"
}
Run Code Online (Sandbox Code Playgroud)