2016-06-14 83 views
0

我已经编写了PowerShell脚本来将新文件复制到服务器上的共享文件夹。PowerShell - 复制多个文件

我想知道是否有一种方法,当我得到子文件夹中的新文件列表后,我可以一起复制它们 - 除了使用for-each并一次复制一个 - 以便我可以添加进度条。

+1

但它更容易为用户提供的foreach对象的进度条; '$ files | foreach {Write-Progress -Activity“复制”-PercentComplete(($ index ++)/ $ files.count)* 100;复制$ _“\\ server \ destination”}' – TessellatingHeckler

+0

谢谢TessellatingHeckler 我不确定这是否会像之前的搜索一样使用.Net copyhere方法通过Windows资源管理器复制并获取进度条这正是我目前在foreach循环内所做的,目前每个文件都会有一个进度条。 虐待这个试试谢谢 – Grantson

回答

0

这样的事情可能是一个起点

# define source and destination folders 
$source = 'C:\temp\music' 
$dest = 'C:\temp\new' 

# get all files in source (not empty directories) 
$files = Get-ChildItem $source -Recurse -File 

$index = 0 
$total = $files.Count 
$starttime = $lasttime = Get-Date 
$results = $files | % { 
    $index++ 
    $currtime = (Get-Date) - $starttime 
    $avg = $currtime.TotalSeconds/$index 
    $last = ((Get-Date) - $lasttime).TotalSeconds 
    $left = $total - $index 
    $WrPrgParam = @{ 
     Activity = (
      "Copying files $(Get-Date -f s)", 
      "Total: $($currtime -replace '\..*')", 
      "Avg: $('{0:N2}' -f $avg)", 
      "Last: $('{0:N2}' -f $last)", 
      "ETA: $('{0:N2}' -f ($avg * $left/60))", 
      "min ($([string](Get-Date).AddSeconds($avg*$left) -replace '^.* '))" 
     ) -join ' ' 
     Status = "$index of $total ($left left) [$('{0:N2}' -f ($index/$total * 100))%]" 
     CurrentOperation = "File: $_" 
     PercentComplete = ($index/$total)*100 
    } 
    Write-Progress @WrPrgParam 
    $lasttime = Get-Date 

    # build destination path for this file 
    $destdir = Join-Path $dest $($(Split-Path $_.fullname) -replace [regex]::Escape($source)) 

    # if it doesn't exist, create it 
    if (!(Test-Path $destdir)) { 
     $null = md $destdir 
    } 

    # if the file.txt already exists, rename it to file-1.txt and so on 
    $num = 1 
    $base = $_.basename 
    $ext = $_.extension 
    $newname = Join-Path $destdir "$base$ext" 
    while (Test-Path $newname) { 
     $newname = Join-Path $destdir "$base-$num$ext" 
     $num++ 
    } 

    # log the source and destination files to the $results variable 
    Write-Output $([pscustomobject]@{ 
     SourceFile = $_.fullname 
     DestFile = $newname 
    }) 

    # finally, copy the file to its new location 
    copy $_.fullname $newname 
} 

# export a list of source files 
$results | Export-Csv c:\temp\copylog.csv -NoTypeInformation 

注:将显示文件总数的进步,无论大小。例如:你有2个文件,一个是1 MB,另一个是50 MB。当第一个文件被复制时,进度将是50%,因为一半的文件被复制。如果你想要总字节数,我强烈建议试试这个函数。只是给它一个来源和目的地。给予单个文件或整个文件夹时,复制

https://github.com/gangstanthony/PowerShell/blob/master/Copy-File.ps1

截图作品:http://i.imgur.com/hT8yoUm.jpg

+0

谢谢安东尼 我看看功能 – Grantson