使用 Robocopy 获取文件列表

m_p*_*wer 3 powershell cmdlets robocopy

我想看看使用 Robocopy 的解决方案是否比使用Get-ChildItem获取给定文件夹(和子文件夹......)内的文件列表更快。

在我的代码中,我使用Get-ChildItemcmdlet 来获取特定文件夹内所有文件的列表,以便在每个文件上循环:

$files = Get-ChildItem "C:\aaa" -Recurse | where {! $_.PIsContainer} # ! because I don't want to list folders
foreach ($file in $files){
...
}
Run Code Online (Sandbox Code Playgroud)

现在,我有 robocopy 命令来获取所有文件的列表,但是,robocopy 的输出是一个字符串。

[string]$result = robocopy "C:\aaa" NULL /l /s /ndl /xx /nc /ns /njh /njs /fp
Run Code Online (Sandbox Code Playgroud)

那么,我如何使用 robocopy 命令的输出来循环每个文件(类似于使用Get-ChildItem?

mjo*_*nor 5

If you're just looking for a faster way to get that list of files, the legacy dir command will do that:

$files = cmd /c dir c:\aaa /b /s /a-d
foreach ($file in $files){
...
}
Run Code Online (Sandbox Code Playgroud)

Edit: Some comparative performance tests-

(measure-command {gci -r |? {-not $_.psiscontainer } }).TotalMilliseconds
(measure-command {gci -r -file}).TotalMilliseconds
(measure-command {(robocopy . NULL /l /s /ndl /xx /nc /ns /njh /njs /fp) }).TotalMilliseconds
(measure-command {cmd /c dir /b /s /a-d }).TotalMilliseconds

627.5434
417.8881
299.9069
86.9364
Run Code Online (Sandbox Code Playgroud)

The tested directory had 6812 files in 420 sub-directories.