我已經編寫了PowerShell腳本來將新文件複製到服務器上的共享文件夾。PowerShell - 複製多個文件
我想知道是否有一種方法,當我得到子文件夾中的新文件列表後,我可以一起復制它們 - 除了使用for-each並一次複製一個 - 以便我可以添加進度條。
我已經編寫了PowerShell腳本來將新文件複製到服務器上的共享文件夾。PowerShell - 複製多個文件
我想知道是否有一種方法,當我得到子文件夾中的新文件列表後,我可以一起復制它們 - 除了使用for-each並一次複製一個 - 以便我可以添加進度條。
這樣的事情可能是一個起點
# 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
謝謝安東尼 我看看功能 – Grantson
但它更容易爲用戶提供的foreach對象的進度條; '$ files | foreach {Write-Progress -Activity「複製」-PercentComplete(($ index ++)/ $ files.count)* 100;複製$ _「\\ server \ destination」}' – TessellatingHeckler
謝謝TessellatingHeckler 我不確定這是否會像之前的搜索一樣使用.Net copyhere方法通過Windows資源管理器複製並獲取進度條這正是我目前在foreach循環內所做的,目前每個文件都會有一個進度條。 虐待這個試試謝謝 – Grantson