How to move a single txt file to the zip in powershell 3

前端 未结 2 1459
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 16:38

I am trying to copy/move one text file to the zip. I don\'t want to unzip it, copy the file and zip it back. Is there any way we can directly copy or move text file to the z

相关标签:
2条回答
  • 2021-01-12 16:56

    >= PowerShell 5.0

    Per @SonnyPuijk's answer above, use Compress-Archive.

    clear-host
    [string]$zipFN = 'c:\temp\myZipFile.zip'
    [string]$fileToZip = 'c:\temp\myTestFile.dat'
    Compress-Archive -Path $fileToZip -Update -DestinationPath $zipFN
    

    < PowerShell 5.0

    To add a single file to an existing zip:

    clear-host
    Add-Type -assembly 'System.IO.Compression'
    Add-Type -assembly 'System.IO.Compression.FileSystem'
    
    [string]$zipFN = 'c:\temp\myZipFile.zip'
    [string]$fileToZip = 'c:\temp\myTestFile.dat'
    [System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Update))
    [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf))
    $ZipFile.Dispose()
    

    To create a single file zip file from scratch:

    Same as above, only replace: [System.IO.Compression.ZipArchiveMode]::Update

    With: [System.IO.Compression.ZipArchiveMode]::Create

    Related Documentation:

    • Compress-Archive: https://technet.microsoft.com/en-us/library/dn841358.aspx
    • CreateEntryFromFile: https://msdn.microsoft.com/en-us/library/hh485720(v=vs.110).aspx
    0 讨论(0)
  • 2021-01-12 16:57

    You can use Compress-Archive for this. Copy-Item doesn't support zip files.

    If you don't have PowerShell v5 you can use either 7Zip command line or .Net

    0 讨论(0)
提交回复
热议问题