【问题标题】:Zip Multiple Folders Individually - Folder Structure单独压缩多个文件夹 - 文件夹结构
【发布时间】:2018-12-12 14:23:40
【问题描述】:

我编写了以下代码,将目录中的多个文件夹压缩成各自的 zip 文件。

#Current path to directory
$fileLocation = read-host "Type/Paste location"
$zipFilesPath = cd "$fileLocation"
$currentDirectory = pwd

$source = Get-ChildItem -Path $currentDirectory -Directory
gci | Where-Object{($_.PSIsContainer)} | foreach-object{$_.Name}

Add-Type -assembly "system.io.compression.filesystem"

Foreach ($s in $source) {
    $zipDestination = Join-path -path $currentDirectory -ChildPath "$($s.name).zip"

    If(Test-path $zipDestination){
        Remove-item $zipDestination
    }
    [io.compression.zipfile]::CreateFromDirectory($s.fullname, $zipDestination)
}

#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”
start .\

单独的拉链部分有效 - 我花了一些时间,但我设法完成了。

例如 zipfolder1

zipfolder2

zipfolder3

zipfolder1.zip

zipfolder2.zip

zipfolder3.zip

我的问题是,当我压缩时,我不只是希望它遍历文件夹并压缩文件夹中的内容,而是按原样压缩文件夹。

脚本当前输出的内容:

zipfolder1.zip > [从 zipfolder1 文件夹中提取的 zip 文件]

我希望它输出什么:

zipfolder.zip > zipfolder1 > [从 zipfolder1 文件夹中提取的 zip 文件]

这可能吗?基本上我想将文件夹本身保存在 zip 中 - 而不仅仅是内容

【问题讨论】:

    标签: powershell zip directory


    【解决方案1】:

    我只使用Compress-Archive commandlet:

    $fileLocation = read-host "Type/Paste location"
    $directories = Get-ChildItem -Path $fileLocation -Directory
    
    foreach ($directory in $directories) {
        Compress-Archive -Path $directory.FullName -DestinationPath "$($directory.FullName).zip" -Force
    }
    

    注意,这只会在目录中有要压缩的内容时压缩。

    【讨论】:

    • 谢谢亚当。这就像一个魅力!我之前尝试过使用 Compress-Archive ,但它对我来说不能正常工作,所以我使用 IO.Compression.ZipFile 来代替它,部分起到了作用。感谢您的帮助,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多