简体   繁体   中英

Delete a file from zip files in powershell 4

I have a function that is working fine. It extract zip file into a destination folder. If the destination folder contains files, it overwrite with the new extract files.Now I wanted to delete/remove one file (bigfile.txt) with a size of 12G before extracting the zip file. How will I do that. Can anyone help me please ? below is the function. Thank you

function Unzip($zipfile, $outdir)
{
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archive = [System.IO.Compression.ZipFile]::OpenRead($zipfile)
foreach ($entry in $archive.Entries)
{
$entryTargetFilePath = [System.IO.Path]::Combine($outdir, $entry.FullName)
$entryDir = [System.IO.Path]::GetDirectoryName($entryTargetFilePath)
#Ensure the directory of the archive entry exists
if(!(Test-Path $entryDir )){
New-Item -ItemType Directory -Path $entryDir | Out-Null
}

#If the entry is not a directory entry, then extract entry
if(!$entryTargetFilePath.EndsWith("\")){
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $entryTargetFilePath, $true);
}

Unzip -zipfile "c:\temp\filezip_1.zip" -outdir "c:\folder_1\extracted_files"
Unzip -zipfile "c:\temp\filezip_2.zip" -outdir "c:\folder_2\extracted_files"e

You are only showing your unzip / extract from zip file effort, not you delete effort, which is the part you are asking about.

Yet what you are asking for it appears to be a duplicate of this discussion and answer.

Remove files from .zip file with Powershell

You are also already calling the System.IO.Compression name space, so the System.IO.Compression.Filesystem has a update and delete method.

Example: (ignore / delete the pause - it's just there so one can see the result at each stage.)

# Zip file path
$zip = 'D:\Temp\MyFile.zip'

# Instantiate the .Net namespace
add-type -AssemblyName 'System.IO.Compression.filesystem'

# Remove a file from a zip archive
foreach ($z in $zip)
{
    # Open the zip for updating
    $tempz = [io.compression.zipfile]::Open($z,'Update')

    "`nShow all files in the zip"
    $tempz.Entries
    Pause

    "`nDelete a specific file"
    ($tempz.Entries | Where FullName -Match 'Test.clixml').Delete()
    Pause

    "`nValidate remove"
    $tempz.Entries
    Pause

    # Clean up / close the zip
    $tempz.Dispose()
}


Show all files in the zip


Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 69
ExternalAttributes : 32
FullName           : newfile.txt
LastWriteTime      : 30-Sep-18 20:52:08 -07:00
Length             : 116
Name               : newfile.txt

Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 41438
ExternalAttributes : 32
FullName           : ps-gps.xml
LastWriteTime      : 02-Oct-18 19:29:44 -07:00
Length             : 767464
Name               : ps-gps.xml

Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 45
ExternalAttributes : 32
FullName           : MyFile.txt
LastWriteTime      : 30-Sep-18 23:31:08 -07:00
Length             : 55
Name               : MyFile.txt

Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 132
ExternalAttributes : 32
FullName           : Test.clixml
LastWriteTime      : 02-Oct-18 17:26:00 -07:00
Length             : 202
Name               : Test.clixml

Press Enter to continue...: 

Delete a specific file
Press Enter to continue...: 

Validate remove
Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 69
ExternalAttributes : 32
FullName           : newfile.txt
LastWriteTime      : 30-Sep-18 20:52:08 -07:00
Length             : 116
Name               : newfile.txt

Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 41438
ExternalAttributes : 32
FullName           : ps-gps.xml
LastWriteTime      : 02-Oct-18 19:29:44 -07:00
Length             : 767464
Name               : ps-gps.xml

Archive            : System.IO.Compression.ZipArchive
CompressedLength   : 45
ExternalAttributes : 32
FullName           : MyFile.txt
LastWriteTime      : 30-Sep-18 23:31:08 -07:00
Length             : 55
Name               : MyFile.txt

Press Enter to continue...: 

Update as per the OP request / multiple files and code merge

The number of zip files you may have to deal with, is really not a concern. Pass as many as you have.

What you did not say is, how are you getting these zip file names. Meaning via Get-ChildItem, or from some text file, the searching for them using the same cmdlet.

Either way the process is the same.

If I doctor your function directly, fixing some stuff along the way. Try this...

function Expand-ZipFilesWithCleanUp
{
    [cmdletbinding()]
    [Alias('ezc')]

    Param
    (
        [string[]]$ZipFiles,
        [string]$Outdir,
        [string] $FilenameToRemove
    )

    # Instantiate the .Net namespace
    add-type -AssemblyName 'System.IO.Compression.filesystem'

    "The number of zip files passed in was $($ZipFiles.Count)"

    # Remove unwanted files
    foreach ($ZipFile in $ZipFiles)
    {
        # Open the zip for updating
        $ProcessZipFile = [io.compression.zipfile]::Open($ZipFile,'Update')

        "`nShow all files in the zip"
        $ProcessZipFile.Entries | Out-GridView -PassThru

        "`nDeleting unwanted file $FilenameToRemove from $ZipFile"
        ($ProcessZipFile.Entries | Where FullName -Match $FilenameToRemove).Delete()

        "`nValidate remove"
        $ProcessZipFile.Entries | Out-GridView -PassThru

        # Clean up / close the zip
        $ProcessZipFile.Dispose()
    }

    #//Begin unzip code



    #//End unzip code

}
Expand-ZipFilesWithCleanUp -ZipFiles (Get-ChildItem -Path 'D:\Temp' -Filter '*.zip').FullName -FilenameToRemove 'Test.clixml'

Again, those..

$ProcessZipFile.Entries | Out-GridView -PassThru

… lines are not needed, they are just a way to pop a dialog to show you what is happening in zip before and after the delete or the given file.

All you have to do now is add in your other code in the space provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM