Zip только файлы, а не каталог - PullRequest
0 голосов
/ 16 ноября 2018

Я использую скрипт с сайта ссылка . Но это застегивает каталог. Скорее, я хочу, чтобы он архивировал только файлы внутри этого каталога, а имя файла zipfile должно быть directory.zip.

Вот функция ZipFolder. Я не уверен, что нужно отредактировать в этом коде, чтобы он мог архивировать только файлы внутри каталога.

function ZipFolder(
    [IO.DirectoryInfo] $directory
) {
    if ($directory -eq $null) {
        throw "Value cannot be null: directory"
    }

    Write-Host ("Creating zip file for folder (" + $directory.FullName + ")...")

    [IO.DirectoryInfo] $parentDir = $directory.Parent

    [string] $zipFileName

    if ($parentDir.FullName.EndsWith("\") -eq $true) {
        # e.g. $parentDir = "C:\"
        $zipFileName = $parentDir.FullName + $directory.Name + ".zip"
    } else {
        $zipFileName = $parentDir.FullName + "\" + $directory.Name + ".zip"
    }

    if (Test-Path $zipFileName) {
        throw "Zip file already exists ($zipFileName)."
    }

    Set-Content $zipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))

    $shellApp = New-Object -ComObject Shell.Application
    $zipFile = $shellApp.NameSpace($zipFileName)

    if ($zipFile -eq $null) {
        throw "Failed to get zip file object."
    }

    [int] $expectedCount = (Get-ChildItem $directory -Force -Recurse).Count
    $expectedCount += 1 # account for the top-level folder

    $zipFile.CopyHere($directory.FullName)

    # wait for CopyHere operation to complete
    WaitForZipOperationToFinish $zipFile $expectedCount

    Write-Host -Fore Green ("Successfully created zip file for folder (" +
        $directory.FullName + ").")
}

#Remove-Item "C:\NotBackedUp\Fabrikam.zip"

[IO.DirectoryInfo] $directory = Get-Item "D:\tmp"
ZipFolder $directory

Ответы [ 2 ]

0 голосов
/ 16 ноября 2018

Я не уверен, какую версию PowerShell вы используете, похоже на v2, и если это правда, действительно обновитесь до минимальной версии v5x. v2 устарела и больше не поддерживается, если память служит.

Используя PSv5, вы можете просто сделать это ...

Get-ChildItem -Path 'e:\temp' -Recurse -Directory | 
ForEach{
    Compress-Archive -Path "$($_.FullName)\*.*" -DestinationPath "$($_.FullName)\$($_.Name).zip" -Verbose
}

Перечисленное выше - это ...

Get-ChildItem -Path 'e:\temp' -Recurse -Directory


# Results

    Directory: E:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       11/15/2018   9:19 PM                Leaf1
d-----       11/15/2018   9:19 PM                Leaf2
d-----       11/15/2018   9:19 PM                Leaf3



Get-ChildItem -Path 'e:\temp' -Recurse -Directory | 
ForEach{
    Get-ChildItem -Path $_.FullName
}

# Results

    Directory: E:\temp\Leaf1


Mode                LastWriteTime         Length Name                                                                                                        
----                -------------         ------ ----                                                                                                        
-a----       11/15/2018   9:19 PM              0 New Bitmap Image.bmp                                                                                        
-a----       11/15/2018   9:19 PM              0 New Text Document.txt                                                                                       


    Directory: E:\temp\Leaf2


Mode                LastWriteTime         Length Name                                                                                                        
----                -------------         ------ ----                                                                                                        
-a----       11/15/2018   9:19 PM              0 New Bitmap Image.bmp                                                                                        
-a----       11/15/2018   9:19 PM              0 New Text Document.txt                                                                                       


    Directory: E:\temp\Leaf3


Mode                LastWriteTime         Length Name                                                                                                        
----                -------------         ------ ----                                                                                                        
-a----       11/15/2018   9:19 PM              0 New Bitmap Image.bmp                                                                                        
-a----       11/15/2018   9:19 PM              0 New Text Document.txt      


Get-ChildItem -Path 'e:\temp' -Recurse -Directory | 
ForEach{
    Compress-Archive -Path "$($_.FullName)\*.*" -DestinationPath "$($_.FullName)\$($_.Name).zip" -WhatIf
}

# Results

What if: Performing the operation "Compress-Archive" on target "
E:\temp\Leaf1\New Bitmap Image.bmp
E:\temp\Leaf1\New Text Document.txt".
What if: Performing the operation "Compress-Archive" on target "
E:\temp\Leaf2\New Bitmap Image.bmp
E:\temp\Leaf2\New Text Document.txt".
What if: Performing the operation "Compress-Archive" on target "
E:\temp\Leaf3\New Bitmap Image.bmp
E:\temp\Leaf3\New Text Document.txt".


Get-ChildItem -Path 'e:\temp' -Recurse -Directory | 
ForEach{
    Compress-Archive -Path "$($_.FullName)\*.*" -DestinationPath "$($_.FullName)\$($_.Name).zip" -Verbose
}

# Results

VERBOSE: Preparing to compress...
VERBOSE: Performing the operation "Compress-Archive" on target "
E:\temp\Leaf1\New Bitmap Image.bmp
E:\temp\Leaf1\New Text Document.txt".
VERBOSE: Adding 'E:\temp\Leaf1\New Bitmap Image.bmp'.
VERBOSE: Adding 'E:\temp\Leaf1\New Text Document.txt'.
VERBOSE: Preparing to compress...
VERBOSE: Performing the operation "Compress-Archive" on target "
E:\temp\Leaf2\New Bitmap Image.bmp
E:\temp\Leaf2\New Text Document.txt".
VERBOSE: Adding 'E:\temp\Leaf2\New Bitmap Image.bmp'.
VERBOSE: Adding 'E:\temp\Leaf2\New Text Document.txt'.
VERBOSE: Preparing to compress...
VERBOSE: Performing the operation "Compress-Archive" on target "
E:\temp\Leaf3\New Bitmap Image.bmp
E:\temp\Leaf3\New Text Document.txt".
VERBOSE: Adding 'E:\temp\Leaf3\New Bitmap Image.bmp'.
VERBOSE: Adding 'E:\temp\Leaf3\New Text Document.txt'.
#>

(Get-ChildItem -Path 'E:\Temp' -Filter '*.zip' -Recurse).FullName

# Results
E:\Temp\Leaf1\Leaf1.zip
E:\Temp\Leaf2\Leaf2.zip
E:\Temp\Leaf3\Leaf3.zip
0 голосов
/ 16 ноября 2018

Найден альтернативный метод из serverfault

$srcdir = "H:\Backup"
$zipFilename = "test.zip"
$zipFilepath = "K:\"
$zipFile = "$zipFilepath$zipFilename"

#Prepare zip file
if(-not (test-path($zipFile))) {
    set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipFile).IsReadOnly = $false  
}

$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipFile)
$files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer}

foreach($file in $files) { 
    $zipPackage.CopyHere($file.FullName)
#using this method, sometimes files can be 'skipped'
#this 'while' loop checks each file is added before moving to the next
    while($zipPackage.Items().Item($file.name) -eq $null){
        Start-sleep -seconds 1
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...