展平目录结构

Flatten directory structure

下面的函数将目录结构展平并根据最后选择的写入日期复制文件。

function mega-copy($srcdir,$destdir,$startdate,$enddate)
{
    $files = Get-ChildItem $SrcDir -recurse | Where-Object { $_.LastWriteTime -ge "$startdate" -and $_.LastWriteTime -le "$enddate" -and $_.PSIsContainer -eq $false };
    $files|foreach($_)
    {
        cp $_.Fullname ($destdir+$_.name) -Verbose
    }
}

这在较小的目录上非常成功,但是当尝试将它用于具有多个子目录和文件数的目录时运行从数十万到数千万,它只是停止.我 运行 将其放置 24 小时,没有复制任何文件,PowerShell 控制台中也没有显示任何内容 window。在此特定实例中,大约有 2700 万个文件。

然而,一个简单的批处理文件完成了这项工作,没有任何问题,尽管它非常慢。

简单的答案是这样的:使用中间变量导致文件移动启动的巨大延迟。结合使用

-and $_.PSIsContainer -eq $false

与简单地使用 -file 开关相反,答案是对我的脚本进行一些简单的修改,结果是:

function mega-copy($srcdir,$destdir,$startdate,$enddate)
{
Get-ChildItem $SrcDir -recurse -File | Where-Object { $_.LastWriteTime -ge "$startdate" -and $_.LastWriteTime -le "$enddate" } | foreach($_) {
                cp $_.Fullname ($destdir+$_.name) -Verbose
}
}