每天我都需要創建以下檔案
C:.
└───1.Jan
├───20000
│ img1.bmp
│ img2.bmp
│ img3.bmp
│
├───20001
│ img1.bmp
│ img2.bmp
│ img3.bmp
│
├───20002
│ img1.bmp
│ img2.bmp
│ img3.bmp
│
├───20003
│ img1.bmp
│ img2.bmp
│ img3.bmp
│
├───20004
│ img1.bmp
│ img2.bmp
│ img3.bmp
│
├───20005
│ img1.bmp
│ img2.bmp
│ img3.bmp
│
└───Entered
我目前讓腳本一次創建一個 zip 檔案,但是有時我可以壓縮 200 多個檔案夾,而且它們的大小不同,所以我想讓這個作業多執行緒。
function Zip-Folders([String] $FolderPath) {
if ($FolderPath -eq '') {
return
}
else {
$FolderNames = Get-ChildItem -Path $FolderPath -Name -Directory -Exclude Enter*
foreach ($i in $FolderNames) {
$TempPath = "$FolderPath\$i"
$TempFileName = "$i Photos"
if (-Not(Get-ChildItem -Path $TempPath | Where-Object {$_.Name -like '*.zip'})) {
Write-Host "[$TempPath] has been compressed to [$TempFileName]."
Compress-Archive -Path $tempPath\* -DestinationPath $tempPath\$TempFileName
}
Else {
Write-Host "[$i] has already been compressed."
}
}
}
}
該代碼通過檔案夾瀏覽器對話框請求檔案夾。
如果有人可以幫助撰寫代碼或指出我可以找到相關資訊的方向,我是 PowerShell 的初學者,但已經完成了一些編程。
如果需要任何其他資訊,請告訴我。
uj5u.com熱心網友回復:
這是您可以使用的方法Runspace,-Threshold根據您要同時壓縮的檔案夾數量使用引數。觀看您的主機資源并小心使用:)
Runspace代碼上的所有學分都歸于這個答案。
function Zip-Folders {
param(
[ValidateScript({Test-Path $_ -PathType Container})]
[String]$FolderPath,
[int]$Threshold = 10
)
begin
{
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $Threshold)
$RunspacePool.Open()
$subFolders = Get-ChildItem -Path $FolderPath -Directory -Exclude Enter*
}
process
{
$runspaces = foreach ($folder in $subFolders)
{
$PSInstance = [powershell]::Create().AddScript({
param($thisFolder)
$fileName = "{0} Photos.zip" -f $thisFolder.Name
$absolutePath = $thisFolder.FullName
$zipPath = Join-Path $absolutePath -ChildPath $fileName
if(-not(Get-ChildItem -Path $absolutePath -Filter *.zip))
{
Compress-Archive -Path $absolutePath\* -DestinationPath $zipPath
"[$absolutePath] has been compressed to [$zipPath]."
continue
}
"[$absolutePath] has already been compressed."
}).AddParameter('thisFolder',$folder)
$PSInstance.RunspacePool = $RunspacePool
[pscustomobject]@{
Instance = $PSInstance
IAResult = $PSInstance.BeginInvoke()
}
}
while($runspaces | Where-Object {-not $_.IAResult.IsCompleted})
{
Start-Sleep -Milliseconds 50
}
$Runspaces | ForEach-Object {
$_.Instance.EndInvoke($_.IAResult)
}
}
end
{
$RunspacePool.Dispose()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/330293.html
上一篇:帶有改造的協程執行緒安全
下一篇:這是升級標準庫鎖的有效方法嗎?
