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

时间:2013-03-01 19:24:10

标签: powershell powershell-v3.0

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

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

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

另外:我需要它递归。

8 个答案:

答案 0 :(得分: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:\\","" }

希望这会让你朝着正确的方向前进。

答案 1 :(得分: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"
}

答案 2 :(得分:3)

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

答案 3 :(得分:2)

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

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

然而,我认为OP要求相对路径(即相对于当前目录),只有@ C.B.的答案解决了这一点。因此,只需添加substring即可:

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

答案 4 :(得分:1)

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

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

答案 5 :(得分:1)

  

将目录列表的PowerShell命令转换为Txt文件:

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

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

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

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

答案 6 :(得分:0)

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

仅在PS 3.0中使用

答案 7 :(得分:0)

检查此链接https://beingsysadmin.com/powershell-to-find-folders-and-files-in-a-deep-nested-directory/

$folderName = "java"
$Output = "C:\Users\John\Desktop\Result.txt"
(gci "C:\SFTP" -Recurse | ?{$_.Name -match [regex]::Escape($folderName)}).FullName | Out-File $Output
相关问题