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

问题描述 投票:6回答:8

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

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

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

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

powershell powershell-v3.0
8个回答
11
投票

您可能正在寻找的是帮助区分文件和文件夹的内容。幸运的是有一个属性调用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

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

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

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


4
投票

它可能像:

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

遵循@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"
}

3
投票
dir | % {
   $p= (split-path -noqualifier $_.fullname).substring(1)
   if($_.psiscontainer) {$p+'\'} else {$p}
}

3
投票

这个显示完整路径,正如其他一些答案那样,但更短:

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

但是,我认为OP要求相对路径(即相对于当前目录),只有@ C.B.的答案解决了这一点。所以通过添加substring我们有这个:

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

1
投票

不是powershell,但您可以在命令提示符下使用以下命令以递归方式将文件列入文本文件:

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

1
投票

目录列表的PowerShell命令到Txt文件:

对于完整路径目录列表(文件夹和文件)到文本文件:

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

对于相对路径目录列表(文件夹和文件)到文本文件:

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

0
投票
(ls $path -r).FullName | % {if((get-item "$_").psiscontainer){"$_\"}else{$_}}

仅在PS 3.0中使用

© www.soinside.com 2019 - 2024. All rights reserved.