我编写了一个PowerShell脚本,用于将新文件复制到服务器上的共享文件夹中。
我想知道是否有办法在我获得子文件夹中的新文件列表后,我可以将它们一起复制 - 除了使用for-each并一次复制一个 - 这样我就可以添加进度条。
答案 0 :(得分: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