我试图将根文件夹(InputFolder)中的每个子文件夹压缩到另一个文件夹(OutputFolder)
我拥有的文件夹结构:
每个文件夹都有 5.000 和 15.000
之间的文件数量我尝试下面的代码,但它没有执行,我也不知道它是否会创建zip文件。
param
(
# The input folder containing the files to zip
[Parameter(Mandatory = $true)]
[string] $InputFolder,
# The output folder that will contain the zip files
[Parameter(Mandatory = $true)]
[string] $OutputFolder
)
#Set-Variable SET_SIZE -option Constant -value 10
$subfolders = Get-ChildItem $InputFolder -Recurse |
Where-Object { $_.PSIsContainer }
ForEach ($s in $subfolders) {
$path = $s #$s variable contains each folder
$path
Set-Location $path.FullName
$fullpath = $path.FullName
$pathName = $path.BaseName
#Get all items
$items = Get-ChildItem
#Verify that there are such items in this directory, catch errors
if ( $(Try { Test-Path $items }
Catch { "Cannot find items in $fullpath.
Sub-folders will be processed afterwards.
ERROR: $_" >> "$InputtFolder\OutputLog.txt" }) ) {
$newpath = $OutputFolder + "\" + $pathName
$newpath
# Create directory if it doesn't exsist
if (!(Test-Path $newpath))
{
$newfld = New-Item -ItemType Directory
-Path $OutputFolder -Name $pathName
}
$src = $newfld.FullName
#move items to newly-created folder
Move-Item $items -destination $src
$dest = "$src.zip"
"Compressing $src to $dest" >> "$InputFolder\OutputLog.txt"
#the following block zips the folder
try{
$zip = New-Object ICSharpCode.SharpZipLib.Zip.FastZip
$zip.CreateZip($dest, $src, $true, ".*")
Remove-Item $src -force -recurse
}
catch {
"Folder could not be compressed. Removal of $src ABORTED.
ERROR: $_" >> "$InputFolder/OutputLog.txt"
}
}
}
答案 0 :(得分:1)
试试这个,
function Compress-Subfolders
{
param
(
[Parameter(Mandatory = $true)][string] $InputFolder,
[Parameter(Mandatory = $true)][string] $OutputFolder
)
$subfolders = Get-ChildItem $InputFolder | Where-Object { $_.PSIsContainer }
ForEach ($s in $subfolders)
{
$path = $s
$path
Set-Location $path.FullName
$fullpath = $path.FullName
$pathName = $path.BaseName
#Get all items
$items = Get-ChildItem
$zipname = $path.name + ".zip"
$zippath = $outputfolder + $zipname
Compress-Archive -Path $items -DestinationPath $zippath
}
}
用法:
Compress-Subfolders -InputFolder c:\your\input\path\ -OutputFolder c:\your\output\path\
输出文件夹必须存在(您可以更改上面的代码来检查和创建文件夹,如果它不存在的话)。
您可以将脚本文件中的函数复制并粘贴到其余代码上方。
问候,罗尼